bitcore-wallet-service/lib/server.js

997 lines
28 KiB
JavaScript
Raw Normal View History

2015-01-27 05:18:45 -08:00
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var async = require('async');
var log = require('npmlog');
log.debug = log.verbose;
2015-02-02 10:56:53 -08:00
var inherits = require('inherits');
var events = require('events');
2015-02-11 18:11:30 -08:00
var nodeutil = require('util');
2015-02-02 10:29:14 -08:00
2015-01-27 11:40:21 -08:00
var Bitcore = require('bitcore');
2015-01-31 14:56:50 -08:00
var PublicKey = Bitcore.PublicKey;
2015-02-01 11:50:58 -08:00
var HDPublicKey = Bitcore.HDPublicKey;
2015-02-06 10:15:54 -08:00
var Address = Bitcore.Address;
2015-01-27 11:40:21 -08:00
var Explorers = require('bitcore-explorers');
2015-01-27 05:18:45 -08:00
2015-02-04 08:31:02 -08:00
var ClientError = require('./clienterror');
2015-02-02 11:00:32 -08:00
var Utils = require('./utils');
2015-01-27 05:18:45 -08:00
var Storage = require('./storage');
2015-02-17 08:11:14 -08:00
var WalletUtils = require('./walletutils');
2015-01-27 11:40:21 -08:00
2015-01-27 05:18:45 -08:00
var Wallet = require('./model/wallet');
var Copayer = require('./model/copayer');
2015-01-27 11:40:21 -08:00
var Address = require('./model/address');
var TxProposal = require('./model/txproposal');
2015-02-18 12:05:02 -08:00
var Notification = require('./model/notification');
2015-01-27 05:18:45 -08:00
2015-02-06 12:56:51 -08:00
var initialized = false;
2015-02-19 12:38:48 -08:00
var storage, blockExplorer;
2015-02-06 12:56:51 -08:00
2015-01-27 07:54:17 -08:00
/**
* Creates an instance of the Copay server.
* @constructor
2015-02-06 12:56:51 -08:00
*/
2015-02-20 12:32:19 -08:00
function WalletService() {
2015-02-20 12:23:42 -08:00
if (!initialized)
2015-02-19 12:38:48 -08:00
throw new Error('Server not initialized');
2015-02-06 12:56:51 -08:00
this.storage = storage;
2015-02-19 12:38:48 -08:00
this.blockExplorer = blockExplorer;
2015-02-12 05:26:13 -08:00
this.notifyTicker = 0;
2015-02-06 12:56:51 -08:00
};
2015-02-20 12:32:19 -08:00
nodeutil.inherits(WalletService, events.EventEmitter);
2015-02-11 10:42:49 -08:00
2015-02-06 12:56:51 -08:00
/**
* Initializes global settings for all instances.
2015-01-28 05:52:45 -08:00
* @param {Object} opts
* @param {Storage} [opts.storage] - The storage provider.
2015-02-19 12:38:48 -08:00
* @param {Storage} [opts.blockExplorer] - The blockExporer provider.
2015-01-27 07:54:17 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.initialize = function(opts) {
2015-02-02 12:07:18 -08:00
opts = opts || {};
2015-02-06 12:56:51 -08:00
storage = opts.storage ||  new Storage();
2015-02-19 12:38:48 -08:00
blockExplorer = opts.blockExplorer;
2015-02-06 12:56:51 -08:00
initialized = true;
2015-01-27 05:18:45 -08:00
};
2015-02-20 12:32:19 -08:00
WalletService.getInstance = function() {
return new WalletService();
2015-02-09 10:30:16 -08:00
};
2015-02-06 12:56:51 -08:00
/**
* Gets an instance of the server after authenticating the copayer.
* @param {Object} opts
* @param {string} opts.copayerId - The copayer id making the request.
* @param {string} opts.message - The contents of the request to be signed.
2015-02-21 14:29:42 -08:00
* @param {string} opts.signature - Signature of message to be verified using the copayer's roPubKey / rwPubKey
* @param {string} opts.readOnly - Signature of message to be verified using the copayer's roPubKey / rwPubKey
2015-02-06 12:56:51 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.getInstanceWithAuth = function(opts, cb) {
2015-02-06 12:56:51 -08:00
2015-02-12 11:42:32 -08:00
if (!Utils.checkRequired(opts, ['copayerId', 'message', 'signature']))
2015-02-12 05:26:13 -08:00
return cb(new ClientError('Required argument missing'));
2015-02-06 12:56:51 -08:00
2015-02-20 12:32:19 -08:00
var server = new WalletService();
2015-02-07 08:13:29 -08:00
server.storage.fetchCopayerLookup(opts.copayerId, function(err, copayer) {
2015-02-06 12:56:51 -08:00
if (err) return cb(err);
2015-02-09 10:30:16 -08:00
if (!copayer) return cb(new ClientError('NOTAUTHORIZED', 'Copayer not found'));
2015-02-06 12:56:51 -08:00
2015-02-21 14:29:42 -08:00
var pubKey = opts.readOnly ? copayer.roPubKey : copayer.rwPubKey;
2015-02-22 18:26:21 -08:00
var isValid = server._verifySignature(opts.message, opts.signature, pubKey);
2015-02-21 14:29:42 -08:00
if (!isValid)
return cb(new ClientError('NOTAUTHORIZED', 'Invalid signature'));
2015-02-02 10:56:53 -08:00
2015-02-06 12:56:51 -08:00
server.copayerId = opts.copayerId;
server.walletId = copayer.walletId;
return cb(null, server);
});
2015-02-02 10:56:53 -08:00
};
2015-01-27 05:18:45 -08:00
2015-02-06 12:56:51 -08:00
2015-01-27 07:54:17 -08:00
/**
* Creates a new wallet.
2015-01-27 11:40:21 -08:00
* @param {Object} opts
2015-01-27 07:54:17 -08:00
* @param {string} opts.id - The wallet id.
* @param {string} opts.name - The wallet name.
* @param {number} opts.m - Required copayers.
* @param {number} opts.n - Total copayers.
* @param {string} opts.pubKey - Public key to verify copayers joining have access to the wallet secret.
* @param {string} [opts.network = 'livenet'] - The Bitcoin network for this wallet.
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.createWallet = function(opts, cb) {
2015-02-02 15:13:13 -08:00
var self = this,
pubKey;
2015-01-27 05:18:45 -08:00
2015-02-11 07:10:47 -08:00
if (!Utils.checkRequired(opts, ['name', 'm', 'n', 'pubKey']))
return cb(new ClientError('Required argument missing'));
2015-02-07 08:13:29 -08:00
2015-02-08 08:16:41 -08:00
if (_.isEmpty(opts.name)) return cb(new ClientError('Invalid wallet name'));
2015-02-07 08:13:29 -08:00
if (!Wallet.verifyCopayerLimits(opts.m, opts.n))
return cb(new ClientError('Invalid combination of required copayers / total copayers'));
2015-02-02 12:07:18 -08:00
var network = opts.network || 'livenet';
2015-02-07 08:13:29 -08:00
if (network != 'livenet' && network != 'testnet')
return cb(new ClientError('Invalid network'));
2015-02-02 10:29:14 -08:00
2015-01-31 14:56:50 -08:00
try {
pubKey = new PublicKey.fromString(opts.pubKey);
} catch (e) {
return cb(e.toString());
};
2015-01-30 06:58:28 -08:00
2015-02-17 15:58:04 -08:00
var wallet = Wallet.create({
2015-02-07 08:13:29 -08:00
name: opts.name,
m: opts.m,
n: opts.n,
2015-02-16 06:17:44 -08:00
network: network,
2015-02-17 22:12:22 -08:00
pubKey: pubKey.toString(),
2015-02-07 08:13:29 -08:00
});
self.storage.storeWallet(wallet, function(err) {
2015-02-13 08:35:20 -08:00
log.debug('Wallet created', wallet.id, network);
return cb(err, wallet.id);
2015-02-02 12:07:18 -08:00
});
2015-01-27 05:18:45 -08:00
};
2015-01-27 07:54:17 -08:00
/**
* Retrieves a wallet from storage.
2015-01-27 11:40:21 -08:00
* @param {Object} opts
2015-02-02 06:55:03 -08:00
* @returns {Object} wallet
2015-01-27 07:54:17 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getWallet = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-27 05:18:45 -08:00
2015-02-06 12:56:51 -08:00
self.storage.fetchWallet(self.walletId, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-04 08:31:02 -08:00
if (!wallet) return cb(new ClientError('Wallet not found'));
2015-02-02 12:07:18 -08:00
return cb(null, wallet);
});
2015-01-27 05:18:45 -08:00
};
2015-01-28 05:36:49 -08:00
2015-02-01 06:41:16 -08:00
/**
* Verifies a signature
* @param text
* @param signature
* @param pubKey
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype._verifySignature = function(text, signature, pubKey) {
2015-02-17 11:42:47 -08:00
return WalletUtils.verifyMessage(text, signature, pubKey);
2015-02-01 06:41:16 -08:00
};
2015-02-11 10:42:49 -08:00
2015-02-11 11:00:16 -08:00
/**
2015-02-11 18:11:30 -08:00
* _notify
2015-02-11 11:00:16 -08:00
*
* @param type
* @param data
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype._notify = function(type, data) {
2015-02-11 10:42:49 -08:00
var self = this;
2015-02-12 11:42:32 -08:00
log.debug('Notification', type, data);
2015-02-11 18:11:30 -08:00
var walletId = self.walletId || data.walletId;
$.checkState(walletId);
2015-02-17 16:20:08 -08:00
var n = Notification.create({
2015-02-11 10:42:49 -08:00
type: type,
data: data,
2015-02-12 05:26:13 -08:00
ticker: this.notifyTicker++,
2015-02-11 10:42:49 -08:00
});
2015-02-11 18:11:30 -08:00
this.storage.storeNotification(walletId, n, function() {
2015-02-11 10:42:49 -08:00
self.emit(n);
});
};
2015-01-27 07:54:17 -08:00
/**
* Joins a wallet in creation.
2015-01-27 11:40:21 -08:00
* @param {Object} opts
2015-01-27 07:54:17 -08:00
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.name - The copayer name.
* @param {number} opts.xPubKey - Extended Public Key for this copayer.
* @param {number} opts.xPubKeySignature - Signature of xPubKey using the wallet pubKey.
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.joinWallet = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-27 05:18:45 -08:00
2015-02-11 07:10:47 -08:00
if (!Utils.checkRequired(opts, ['walletId', 'name', 'xPubKey', 'xPubKeySignature']))
return cb(new ClientError('Required argument missing'));
2015-02-02 10:29:14 -08:00
2015-02-12 11:42:32 -08:00
if (_.isEmpty(opts.name))
2015-02-12 05:26:13 -08:00
return cb(new ClientError('Invalid copayer name'));
2015-02-08 08:36:19 -08:00
2015-02-02 15:13:13 -08:00
Utils.runLocked(opts.walletId, cb, function(cb) {
2015-02-06 12:56:51 -08:00
self.storage.fetchWallet(opts.walletId, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-06 12:56:51 -08:00
if (!wallet) return cb(new ClientError('Wallet not found'));
2015-02-01 06:41:16 -08:00
if (!self._verifySignature(opts.xPubKey, opts.xPubKeySignature, wallet.pubKey)) {
2015-02-04 08:31:02 -08:00
return cb(new ClientError());
2015-02-01 06:41:16 -08:00
}
2015-02-02 06:55:03 -08:00
if (_.find(wallet.copayers, {
xPubKey: opts.xPubKey
2015-02-04 08:31:02 -08:00
})) return cb(new ClientError('CINWALLET', 'Copayer already in wallet'));
2015-02-17 12:36:45 -08:00
2015-02-12 11:42:32 -08:00
if (wallet.copayers.length == wallet.n)
2015-02-12 05:26:13 -08:00
return cb(new ClientError('WFULL', 'Wallet full'));
2015-02-02 06:55:03 -08:00
2015-02-17 15:26:58 -08:00
var copayer = Copayer.create({
2015-02-02 12:07:18 -08:00
name: opts.name,
xPubKey: opts.xPubKey,
xPubKeySignature: opts.xPubKeySignature,
2015-02-02 04:36:55 -08:00
copayerIndex: wallet.copayers.length,
2015-02-02 12:07:18 -08:00
});
2015-02-02 15:13:13 -08:00
2015-02-17 12:36:45 -08:00
self.storage.fetchCopayerLookup(copayer.id, function(err, res) {
2015-02-12 19:00:54 -08:00
if (err) return cb(err);
2015-02-17 12:36:45 -08:00
if (res)
return cb(new ClientError('CREGISTERED', 'Copayer ID already registered on server'));
2015-02-17 12:36:45 -08:00
wallet.addCopayer(copayer);
self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) {
if (err) return cb(err);
self._notify('NewCopayer', {
walletId: opts.walletId,
copayerId: copayer.id,
copayerName: copayer.name,
});
return cb(null, {
copayerId: copayer.id,
wallet: wallet
});
2015-02-12 19:00:54 -08:00
});
2015-02-02 12:07:18 -08:00
});
});
});
2015-01-27 05:18:45 -08:00
};
2015-01-27 11:40:21 -08:00
/**
* Creates a new address.
* @param {Object} opts
2015-02-02 06:55:03 -08:00
* @returns {Address} address
2015-01-27 11:40:21 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.createAddress = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-02-06 12:56:51 -08:00
Utils.runLocked(self.walletId, cb, function(cb) {
self.getWallet({}, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-12 11:42:32 -08:00
if (!wallet.isComplete())
2015-02-12 05:26:13 -08:00
return cb(new ClientError('Wallet is not complete'));
2015-02-02 15:13:13 -08:00
var address = wallet.createAddress(false);
2015-02-02 11:32:13 -08:00
2015-02-08 15:46:02 -08:00
self.storage.storeAddressAndWallet(wallet, address, function(err) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-04 11:18:36 -08:00
2015-02-11 18:11:30 -08:00
self._notify('NewAddress');
2015-02-08 15:46:02 -08:00
return cb(null, address);
2015-02-02 12:07:18 -08:00
});
});
});
2015-01-27 05:18:45 -08:00
};
2015-02-03 12:32:40 -08:00
/**
* Get all addresses.
* @param {Object} opts
* @returns {Address[]}
*/
2015-02-22 08:04:23 -08:00
WalletService.prototype.getMainAddresses = function(opts, cb) {
2015-02-03 12:32:40 -08:00
var self = this;
2015-02-06 12:56:51 -08:00
self.storage.fetchAddresses(self.walletId, function(err, addresses) {
2015-02-03 12:32:40 -08:00
if (err) return cb(err);
var onlyMain = _.reject(addresses, {
isChange: true
});
return cb(null, onlyMain);
2015-02-03 12:32:40 -08:00
});
};
2015-01-28 07:06:34 -08:00
/**
* Verifies that a given message was actually sent by an authorized copayer.
* @param {Object} opts
* @param {string} opts.message - The message to verify.
* @param {string} opts.signature - The signature of message to verify.
* @returns {truthy} The result of the verification.
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.verifyMessageSignature = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-28 07:06:34 -08:00
2015-02-11 07:10:47 -08:00
if (!Utils.checkRequired(opts, ['message', 'signature']))
return cb(new ClientError('Required argument missing'));
2015-02-02 10:29:14 -08:00
2015-02-06 12:56:51 -08:00
self.getWallet({}, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-01-28 09:21:09 -08:00
2015-02-06 12:56:51 -08:00
var copayer = wallet.getCopayer(self.copayerId);
2015-01-28 07:06:34 -08:00
2015-02-21 15:20:58 -08:00
var isValid = self._verifySignature(opts.message, opts.signature, copayer.rwPubKey);
2015-02-02 12:07:18 -08:00
return cb(null, isValid);
});
2015-01-28 07:06:34 -08:00
};
2015-01-27 05:18:45 -08:00
2015-02-20 12:32:19 -08:00
WalletService.prototype._getBlockExplorer = function(provider, network) {
2015-02-02 12:07:18 -08:00
var url;
2015-02-22 18:26:21 -08:00
function getTransactionsInsight(url, addresses, cb) {
var request = require('request');
request({
method: "POST",
url: url + '/api/addrs/txs',
json: {
addrs: [].concat(addresses).join(',')
}
}, function(err, res, body) {
if (err || res.statusCode != 200) return cb(err || res);
return cb(null, body);
});
};
2015-02-19 12:38:48 -08:00
if (this.blockExplorer)
return this.blockExplorer;
2015-02-02 12:07:18 -08:00
switch (provider) {
default:
case 'insight':
switch (network) {
default:
case 'livenet':
url = 'https://insight.bitpay.com:443';
break;
case 'testnet':
url = 'https://test-insight.bitpay.com:443'
break;
}
2015-02-22 18:26:21 -08:00
var bc = new Explorers.Insight(url, network);
bc.getTransactions = _.bind(getTransactionsInsight, bc, url);
return bc;
2015-02-02 12:07:18 -08:00
break;
}
2015-01-27 05:18:45 -08:00
};
2015-02-05 12:22:38 -08:00
/**
* _getUtxos
*
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype._getUtxos = function(cb) {
2015-02-02 12:07:18 -08:00
var self = this;
// Get addresses for this wallet
2015-02-06 12:56:51 -08:00
self.storage.fetchAddresses(self.walletId, function(err, addresses) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-13 11:57:28 -08:00
if (addresses.length == 0)
2015-02-13 07:55:07 -08:00
return cb(null, []);
2015-02-02 12:07:18 -08:00
2015-02-04 06:43:12 -08:00
var addressStrs = _.pluck(addresses, 'address');
var addressToPath = _.indexBy(addresses, 'address'); // TODO : check performance
2015-02-13 08:35:20 -08:00
var networkName = Bitcore.Address(addressStrs[0]).toObject().network;
2015-02-02 12:07:18 -08:00
2015-02-06 10:15:54 -08:00
var bc = self._getBlockExplorer('insight', networkName);
2015-02-13 13:24:35 -08:00
bc.getUnspentUtxos(addressStrs, function(err, inutxos) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-13 13:24:35 -08:00
var utxos = _.map(inutxos, function(i) {
2015-02-21 20:01:15 -08:00
return _.pick(i.toObject(), ['txid', 'vout', 'address', 'scriptPubKey', 'amount', 'satoshis']);
2015-02-13 13:24:35 -08:00
});
2015-02-06 12:56:51 -08:00
self.getPendingTxs({}, function(err, txps) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-21 06:31:15 -08:00
var utxoKey = function(utxo) {
return utxo.txid + '|' + utxo.vout
};
2015-02-02 12:07:18 -08:00
var inputs = _.chain(txps)
.pluck('inputs')
.flatten()
2015-02-21 06:31:15 -08:00
.map(utxoKey)
.value();
2015-02-02 12:07:18 -08:00
2015-02-04 11:18:36 -08:00
var dictionary = _.reduce(utxos, function(memo, utxo) {
2015-02-21 06:31:15 -08:00
memo[utxoKey(utxo)] = utxo;
return memo;
}, {});
2015-02-02 12:07:18 -08:00
2015-02-02 15:13:13 -08:00
_.each(inputs, function(input) {
2015-02-02 12:07:18 -08:00
if (dictionary[input]) {
dictionary[input].locked = true;
}
});
2015-02-03 18:17:06 -08:00
2015-02-04 06:43:12 -08:00
// Needed for the clients to sign UTXOs
_.each(utxos, function(utxo) {
2015-02-18 11:47:15 -08:00
utxo.satoshis = utxo.satoshis ? +utxo.satoshis : Utils.strip(utxo.amount * 1e8);
delete utxo.amount;
2015-02-04 06:43:12 -08:00
utxo.path = addressToPath[utxo.address].path;
utxo.publicKeys = addressToPath[utxo.address].publicKeys;
});
2015-02-03 18:17:06 -08:00
2015-02-02 12:07:18 -08:00
return cb(null, utxos);
});
});
});
2015-01-27 05:18:45 -08:00
};
2015-01-30 12:37:30 -08:00
/**
* Creates a new transaction proposal.
* @param {Object} opts
2015-02-02 06:55:03 -08:00
* @returns {Object} balance - Total amount & locked amount.
2015-01-30 12:37:30 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getBalance = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-30 12:37:30 -08:00
2015-02-06 12:56:51 -08:00
self._getUtxos(function(err, utxos) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-01-30 12:37:30 -08:00
2015-02-02 12:07:18 -08:00
var balance = {};
2015-02-03 18:17:06 -08:00
balance.totalAmount = Utils.strip(_.reduce(utxos, function(sum, utxo) {
2015-02-18 11:47:15 -08:00
return sum + utxo.satoshis;
2015-02-03 18:17:06 -08:00
}, 0));
balance.lockedAmount = Utils.strip(_.reduce(_.filter(utxos, {
2015-02-02 15:13:13 -08:00
locked: true
}), function(sum, utxo) {
2015-02-18 11:47:15 -08:00
return sum + utxo.satoshis;
2015-02-03 18:17:06 -08:00
}, 0));
2015-01-30 12:37:30 -08:00
2015-02-02 12:07:18 -08:00
return cb(null, balance);
});
2015-01-30 12:37:30 -08:00
};
2015-02-20 12:32:19 -08:00
WalletService.prototype._selectUtxos = function(txp, utxos) {
2015-02-02 12:07:18 -08:00
var i = 0;
var total = 0;
var selected = [];
var inputs = _.sortBy(utxos, 'amount');
2015-02-02 12:07:18 -08:00
while (i < inputs.length) {
selected.push(inputs[i]);
2015-02-18 11:47:15 -08:00
total += inputs[i].satoshis;
2015-02-04 11:18:36 -08:00
2015-02-16 10:00:41 -08:00
if (total >= txp.amount + Bitcore.Transaction.FEE_PER_KB) {
2015-02-16 09:27:01 -08:00
try {
// Check if there are enough fees
txp.inputs = selected;
var raw = txp.getRawTx();
return;
} catch (ex) {
2015-02-16 10:00:41 -08:00
if (ex.name != 'bitcore.ErrorTransactionFeeError') {
throw ex.message;
}
2015-02-16 09:27:01 -08:00
}
2015-02-02 12:07:18 -08:00
}
i++;
};
2015-02-16 09:27:01 -08:00
txp.inputs = null;
return;
2015-01-30 13:29:46 -08:00
};
2015-01-27 05:18:45 -08:00
2015-01-27 07:54:17 -08:00
/**
* Creates a new transaction proposal.
2015-01-27 11:40:21 -08:00
* @param {Object} opts
2015-01-27 07:54:17 -08:00
* @param {string} opts.toAddress - Destination address.
* @param {number} opts.amount - Amount to transfer in satoshi.
* @param {string} opts.message - A message to attach to this transaction.
2015-02-10 05:22:23 -08:00
* @param {string} opts.proposalSignature - S(toAddress + '|' + amount + '|' + message). Used by other copayers to verify the proposal. Optional in 1-of-1 wallets.
2015-02-02 06:55:03 -08:00
* @returns {TxProposal} Transaction proposal.
2015-01-27 07:54:17 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.createTx = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-27 05:18:45 -08:00
2015-02-13 11:57:28 -08:00
if (!Utils.checkRequired(opts, ['toAddress', 'amount', 'proposalSignature']))
2015-02-11 07:10:47 -08:00
return cb(new ClientError('Required argument missing'));
2015-02-02 10:29:14 -08:00
2015-02-08 13:29:58 -08:00
Utils.runLocked(self.walletId, cb, function(cb) {
self.getWallet({}, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-08 13:29:58 -08:00
if (!wallet.isComplete()) return cb(new ClientError('Wallet is not complete'));
2015-02-10 05:22:23 -08:00
var copayer = wallet.getCopayer(self.copayerId);
2015-02-17 08:11:14 -08:00
var hash = WalletUtils.getProposalHash(opts.toAddress, opts.amount, opts.message);
2015-02-21 15:20:58 -08:00
if (!self._verifySignature(hash, opts.proposalSignature, copayer.rwPubKey))
2015-02-11 18:11:30 -08:00
return cb(new ClientError('Invalid proposal signature'));
2015-01-28 12:06:29 -08:00
2015-02-08 14:10:06 -08:00
var toAddress;
try {
toAddress = new Bitcore.Address(opts.toAddress);
} catch (ex) {
return cb(new ClientError('INVALIDADDRESS', 'Invalid address'));
}
2015-02-11 18:11:30 -08:00
if (toAddress.network != wallet.getNetworkName())
return cb(new ClientError('INVALIDADDRESS', 'Incorrect address network'));
2015-02-08 14:10:06 -08:00
2015-02-16 10:00:41 -08:00
if (opts.amount < Bitcore.Transaction.DUST_AMOUNT)
2015-02-16 09:41:12 -08:00
return cb(new ClientError('DUSTAMOUNT', 'Amount below dust threshold'));
2015-02-08 13:29:58 -08:00
self._getUtxos(function(err, utxos) {
if (err) return cb(err);
2015-02-03 18:17:06 -08:00
2015-02-08 13:29:58 -08:00
var changeAddress = wallet.createAddress(true);
2015-01-30 12:37:30 -08:00
2015-02-08 13:29:58 -08:00
utxos = _.reject(utxos, {
locked: true
});
2015-01-30 12:37:30 -08:00
2015-02-17 16:20:08 -08:00
var txp = TxProposal.create({
2015-02-08 13:29:58 -08:00
creatorId: self.copayerId,
toAddress: opts.toAddress,
amount: opts.amount,
message: opts.message,
2015-02-19 11:21:50 -08:00
proposalSignature: opts.proposalSignature,
changeAddress: changeAddress,
2015-02-08 13:29:58 -08:00
requiredSignatures: wallet.m,
2015-02-09 09:20:25 -08:00
requiredRejections: Math.min(wallet.m, wallet.n - wallet.m + 1),
2015-02-08 13:29:58 -08:00
});
2015-01-28 07:06:34 -08:00
2015-02-16 10:00:41 -08:00
try {
self._selectUtxos(txp, utxos);
} catch (ex) {
2015-02-22 08:04:23 -08:00
console.log('[server.js.523:ex:]', ex); //TODO
2015-02-16 10:00:41 -08:00
return cb(new ClientError(ex));
2015-02-08 13:29:58 -08:00
}
2015-02-04 06:43:12 -08:00
2015-02-16 10:00:41 -08:00
if (!txp.inputs)
return cb(new ClientError('INSUFFICIENTFUNDS', 'Insufficient funds'));
2015-02-08 13:29:58 -08:00
txp.inputPaths = _.pluck(txp.inputs, 'path');
2015-02-08 15:46:02 -08:00
self.storage.storeAddressAndWallet(wallet, changeAddress, function(err) {
2015-02-08 13:29:58 -08:00
if (err) return cb(err);
2015-01-28 07:06:34 -08:00
2015-02-08 15:46:02 -08:00
self.storage.storeTx(wallet.id, txp, function(err) {
2015-02-08 13:29:58 -08:00
if (err) return cb(err);
2015-02-11 18:11:30 -08:00
self._notify('NewTxProposal', {
amount: opts.amount
});
2015-02-08 15:46:02 -08:00
return cb(null, txp);
});
2015-02-08 13:29:58 -08:00
});
2015-02-02 12:07:18 -08:00
});
});
});
2015-02-02 15:13:13 -08:00
};
2015-01-28 07:06:34 -08:00
2015-02-04 10:45:08 -08:00
/**
* Retrieves a tx from storage.
* @param {Object} opts
* @param {string} opts.id - The tx id.
* @returns {Object} txProposal
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getTx = function(opts, cb) {
2015-02-04 10:45:08 -08:00
var self = this;
2015-02-06 12:56:51 -08:00
self.storage.fetchTx(self.walletId, opts.id, function(err, txp) {
2015-02-04 10:45:08 -08:00
if (err) return cb(err);
if (!txp) return cb(new ClientError('Transaction proposal not found'));
return cb(null, txp);
});
};
2015-02-09 13:07:15 -08:00
/**
2015-02-10 11:11:44 -08:00
* removeWallet
*
* @param opts
* @param cb
* @return {undefined}
2015-02-09 13:07:15 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.removeWallet = function(opts, cb) {
2015-02-10 11:11:44 -08:00
var self = this;
Utils.runLocked(self.walletId, cb, function(cb) {
self.storage.removeWallet(self.walletId, cb);
});
2015-02-09 13:07:15 -08:00
};
2015-02-10 11:30:58 -08:00
/**
* removePendingTx
*
* @param opts
2015-02-15 08:03:48 -08:00
* @param {string} opts.txProposalId - The tx id.
2015-02-10 11:30:58 -08:00
* @return {undefined}
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.removePendingTx = function(opts, cb) {
2015-02-10 11:30:58 -08:00
var self = this;
2015-02-15 08:03:48 -08:00
if (!Utils.checkRequired(opts, ['txProposalId']))
2015-02-10 11:30:58 -08:00
return cb(new ClientError('Required argument missing'));
2015-02-11 06:41:05 -08:00
Utils.runLocked(self.walletId, cb, function(cb) {
2015-02-10 11:30:58 -08:00
2015-02-11 07:05:21 -08:00
self.getTx({
2015-02-15 08:03:48 -08:00
id: opts.txProposalId,
2015-02-11 07:05:21 -08:00
}, function(err, txp) {
2015-02-10 11:30:58 -08:00
if (err) return cb(err);
if (!txp.isPending())
2015-02-23 13:31:27 -08:00
return cb(new ClientError('TXNOTPENDING', 'Transaction proposal not pending'));
2015-02-10 11:30:58 -08:00
2015-02-10 13:04:50 -08:00
if (txp.creatorId !== self.copayerId)
2015-02-11 07:05:21 -08:00
return cb(new ClientError('Only creators can remove pending proposals'));
2015-02-10 13:04:50 -08:00
2015-02-10 11:30:58 -08:00
var actors = txp.getActors();
2015-02-11 07:05:21 -08:00
if (actors.length > 1 || (actors.length == 1 && actors[0] !== self.copayerId))
2015-02-23 13:31:27 -08:00
return cb(new ClientError('TXACTIONED', 'Cannot remove a proposal signed/rejected by other copayers'));
2015-02-10 11:30:58 -08:00
2015-02-11 18:11:30 -08:00
self._notify('transactionProposalRemoved');
2015-02-15 08:03:48 -08:00
self.storage.removeTx(self.walletId, txp.id, cb);
2015-02-10 11:30:58 -08:00
});
});
};
2015-02-09 13:07:15 -08:00
2015-02-20 12:32:19 -08:00
WalletService.prototype._broadcastTx = function(txp, cb) {
2015-02-16 09:27:01 -08:00
var raw;
try {
raw = txp.getRawTx();
} catch (ex) {
return cb(ex);
}
2015-02-06 10:51:40 -08:00
var bc = this._getBlockExplorer('insight', txp.getNetworkName());
2015-02-05 12:22:38 -08:00
bc.broadcast(raw, function(err, txid) {
return cb(err, txid);
})
2015-01-28 08:28:18 -08:00
};
2015-01-28 07:06:34 -08:00
/**
* Sign a transaction proposal.
* @param {Object} opts
2015-01-28 08:28:18 -08:00
* @param {string} opts.txProposalId - The identifier of the transaction.
2015-02-04 11:18:36 -08:00
* @param {string} opts.signatures - The signatures of the inputs of this tx for this copayer (in apperance order)
2015-01-28 07:06:34 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.signTx = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-28 07:06:34 -08:00
2015-02-11 07:10:47 -08:00
if (!Utils.checkRequired(opts, ['txProposalId', 'signatures']))
return cb(new ClientError('Required argument missing'));
2015-02-02 10:29:14 -08:00
2015-02-06 12:56:51 -08:00
self.getWallet({}, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-01-27 05:18:45 -08:00
2015-02-05 10:50:18 -08:00
self.getTx({
id: opts.txProposalId
}, function(err, txp) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-10 11:30:58 -08:00
2015-02-05 10:50:18 -08:00
var action = _.find(txp.actions, {
2015-02-10 11:30:58 -08:00
copayerId: self.copayerId
2015-02-05 10:50:18 -08:00
});
2015-02-05 12:22:38 -08:00
if (action)
2015-02-05 10:50:18 -08:00
return cb(new ClientError('CVOTED', 'Copayer already voted on this transaction proposal'));
2015-02-23 13:31:27 -08:00
if (!txp.isPending())
2015-02-05 10:50:18 -08:00
return cb(new ClientError('TXNOTPENDING', 'The transaction proposal is not pending'));
2015-01-28 11:40:07 -08:00
2015-02-06 12:56:51 -08:00
var copayer = wallet.getCopayer(self.copayerId);
2015-01-27 05:18:45 -08:00
2015-02-13 16:00:12 -08:00
if (!txp.sign(self.copayerId, opts.signatures, copayer.xPubKey))
2015-02-05 10:50:18 -08:00
return cb(new ClientError('BADSIGNATURES', 'Bad signatures'));
2015-02-06 12:56:51 -08:00
self.storage.storeTx(self.walletId, txp, function(err) {
2015-02-05 10:50:18 -08:00
if (err) return cb(err);
2015-02-11 18:11:30 -08:00
self._notify('TxProposalAcceptedBy', {
txProposalId: opts.txProposalId,
copayerId: self.copayerId,
});
2015-02-19 11:21:50 -08:00
// TODO: replace with .isAccepted()
2015-02-05 10:50:18 -08:00
if (txp.status == 'accepted') {
2015-02-11 18:11:30 -08:00
self._notify('TxProposalFinallyAccepted', {
txProposalId: opts.txProposalId,
});
2015-02-05 10:50:18 -08:00
}
2015-02-25 11:00:41 -08:00
return cb(null, txp);
2015-02-05 10:50:18 -08:00
});
2015-02-02 12:07:18 -08:00
});
});
2015-02-02 06:55:03 -08:00
};
2015-01-27 05:18:45 -08:00
2015-02-15 13:52:48 -08:00
/**
* Broadcast a transaction proposal.
* @param {Object} opts
* @param {string} opts.txProposalId - The identifier of the transaction.
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.broadcastTx = function(opts, cb) {
2015-02-15 13:52:48 -08:00
var self = this;
if (!Utils.checkRequired(opts, ['txProposalId']))
return cb(new ClientError('Required argument missing'));
self.getWallet({}, function(err, wallet) {
if (err) return cb(err);
self.getTx({
id: opts.txProposalId
}, function(err, txp) {
if (err) return cb(err);
if (txp.status == 'broadcasted')
return cb(new ClientError('TXALREADYBROADCASTED', 'The transaction proposal is already broadcasted'));
if (txp.status != 'accepted')
return cb(new ClientError('TXNOTACCEPTED', 'The transaction proposal is not accepted'));
self._broadcastTx(txp, function(err, txid) {
if (err) return cb(err);
txp.setBroadcasted(txid);
self.storage.storeTx(self.walletId, txp, function(err) {
if (err) return cb(err);
self._notify('NewOutgoingTx', {
txProposalId: opts.txProposalId,
txid: txid
});
2015-02-25 13:16:09 -08:00
return cb(null, txp);
2015-02-15 13:52:48 -08:00
});
});
});
});
};
2015-01-29 09:57:26 -08:00
/**
* Reject a transaction proposal.
* @param {Object} opts
* @param {string} opts.txProposalId - The identifier of the transaction.
2015-02-02 10:29:14 -08:00
* @param {string} [opts.reason] - A message to other copayers explaining the rejection.
2015-01-29 09:57:26 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.rejectTx = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-29 09:57:26 -08:00
2015-02-11 07:10:47 -08:00
if (!Utils.checkRequired(opts, ['txProposalId']))
return cb(new ClientError('Required argument missing'));
2015-02-02 10:29:14 -08:00
2015-02-04 11:27:36 -08:00
self.getTx({
id: opts.txProposalId
}, function(err, txp) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-11 06:27:52 -08:00
2015-02-02 15:13:13 -08:00
var action = _.find(txp.actions, {
2015-02-06 12:56:51 -08:00
copayerId: self.copayerId
2015-02-02 15:13:13 -08:00
});
2015-02-11 18:11:30 -08:00
if (action)
return cb(new ClientError('CVOTED', 'Copayer already voted on this transaction proposal'));
if (txp.status != 'pending')
return cb(new ClientError('TXNOTPENDING', 'The transaction proposal is not pending'));
2015-01-29 09:57:26 -08:00
2015-02-15 10:46:29 -08:00
txp.reject(self.copayerId, opts.reason);
2015-01-29 09:57:26 -08:00
2015-02-06 12:56:51 -08:00
self.storage.storeTx(self.walletId, txp, function(err) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-01-29 09:57:26 -08:00
2015-02-11 18:11:30 -08:00
self._notify('TxProposalRejectedBy', {
txProposalId: opts.txProposalId,
copayerId: self.copayerId,
});
if (txp.status == 'rejected') {
self._notify('TxProposalFinallyRejected', {
txProposalId: opts.txProposalId,
});
};
2015-02-19 13:11:57 -08:00
return cb(null, txp);
2015-02-02 12:07:18 -08:00
});
});
2015-01-29 09:57:26 -08:00
};
2015-01-28 07:06:34 -08:00
/**
2015-02-21 17:35:12 -08:00
* Retrieves pending transaction proposals.
2015-01-28 07:06:34 -08:00
* @param {Object} opts
2015-02-02 06:55:03 -08:00
* @returns {TxProposal[]} Transaction proposal.
2015-01-28 07:06:34 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getPendingTxs = function(opts, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-01-27 05:18:45 -08:00
2015-02-06 12:51:21 -08:00
self.storage.fetchPendingTxs(self.walletId, function(err, txps) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-01-28 12:40:37 -08:00
2015-02-06 23:09:45 -08:00
return cb(null, txps);
2015-02-02 12:07:18 -08:00
});
2015-01-27 05:18:45 -08:00
};
2015-02-06 23:09:45 -08:00
/**
2015-02-21 17:35:12 -08:00
* Retrieves all transaction proposals in the range (maxTs-minTs)
2015-02-12 05:26:13 -08:00
* Times are in UNIX EPOCH
*
2015-02-06 23:09:45 -08:00
* @param {Object} opts.minTs (defaults to 0)
* @param {Object} opts.maxTs (defaults to now)
* @param {Object} opts.limit
2015-02-11 18:13:19 -08:00
* @returns {TxProposal[]} Transaction proposals, first newer
2015-02-06 23:09:45 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getTxs = function(opts, cb) {
2015-02-06 23:09:45 -08:00
var self = this;
self.storage.fetchTxs(self.walletId, opts, function(err, txps) {
if (err) return cb(err);
return cb(null, txps);
});
};
2015-02-11 18:13:19 -08:00
/**
2015-02-21 17:35:12 -08:00
* Retrieves notifications in the range (maxTs-minTs).
2015-02-12 05:26:13 -08:00
* Times are in UNIX EPOCH. Order is assured even for events with the same time
*
2015-02-11 18:13:19 -08:00
* @param {Object} opts.minTs (defaults to 0)
* @param {Object} opts.maxTs (defaults to now)
* @param {Object} opts.limit
2015-02-12 05:26:13 -08:00
* @param {Object} opts.reverse (default false)
2015-02-12 11:42:32 -08:00
* @returns {Notification[]} Notifications
2015-02-11 18:13:19 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.prototype.getNotifications = function(opts, cb) {
2015-02-11 18:13:19 -08:00
var self = this;
self.storage.fetchNotifications(self.walletId, opts, function(err, notifications) {
if (err) return cb(err);
return cb(null, notifications);
});
};
2015-02-21 17:35:12 -08:00
WalletService.prototype._normalizeTxHistory = function(txs) {
return _.map(txs, function(tx) {
var inputs = _.map(tx.vin, function(item) {
return {
address: item.addr,
amount: item.valueSat,
}
});
var outputs = _.map(tx.vout, function(item) {
var itemAddr;
// If classic multisig, ignore
if (item.scriptPubKey && item.scriptPubKey.addresses.length == 1) {
itemAddr = item.scriptPubKey.addresses[0];
}
return {
address: itemAddr,
amount: parseInt((item.value * 1e8).toFixed(0)),
}
});
return {
txid: tx.txid,
confirmations: tx.confirmations,
fees: parseInt((tx.fees * 1e8).toFixed(0)),
2015-02-22 18:26:21 -08:00
time: !_.isNaN(tx.time) ? tx.time : Math.floor(Date.now() / 1000),
2015-02-21 17:35:12 -08:00
inputs: inputs,
outputs: outputs,
};
});
};
/**
* Retrieves all transactions (incoming & outgoing) in the range (maxTs-minTs)
* Times are in UNIX EPOCH
*
* @param {Object} opts.minTs (defaults to 0)
* @param {Object} opts.maxTs (defaults to now)
* @param {Object} opts.limit
* @returns {TxProposal[]} Transaction proposals, first newer
*/
WalletService.prototype.getTxHistory = function(opts, cb) {
var self = this;
function decorate(txs, addresses, proposals) {
function sum(items, isMine, isChange) {
var filter = {};
if (_.isBoolean(isMine)) filter.isMine = isMine;
if (_.isBoolean(isChange)) filter.isChange = isChange;
return _.reduce(_.where(items, filter),
function(memo, item) {
return memo + item.amount;
}, 0);
};
var indexedAddresses = _.indexBy(addresses, 'address');
var indexedProposals = _.indexBy(proposals, 'txid');
_.each(txs, function(tx) {
_.each(tx.inputs.concat(tx.outputs), function(item) {
var address = indexedAddresses[item.address];
item.isMine = !!address;
item.isChange = address ? address.isChange : false;
});
var amountIn = sum(tx.inputs, true);
var amountOut = sum(tx.outputs, true, false);
var amountOutChange = sum(tx.outputs, true, true);
var amount;
if (amountIn == (amountOut + amountOutChange + (amountIn > 0 ? tx.fees : 0))) {
tx.action = 'moved';
amount = amountOut;
} else {
amount = amountIn - amountOut - amountOutChange - (amountIn > 0 ? tx.fees : 0);
tx.action = amount > 0 ? 'sent' : 'received';
}
tx.amount = Math.abs(amount);
if (tx.action == 'sent' || tx.action == 'moved') {
tx.addressTo = tx.outputs[0].address;
};
2015-02-11 18:13:19 -08:00
2015-02-21 17:35:12 -08:00
delete tx.inputs;
delete tx.outputs;
var proposal = indexedProposals[tx.txid];
if (proposal) {
2015-02-23 12:15:38 -08:00
tx.proposalId = proposal.id;
tx.creatorName = proposal.creatorName;
2015-02-21 17:35:12 -08:00
tx.message = proposal.message;
2015-02-22 18:26:21 -08:00
tx.actions = _.map(proposal.actions, function(action) {
return _.pick(action, ['createdOn', 'type', 'copayerId', 'copayerName', 'comment']);
});
2015-02-21 17:35:12 -08:00
// tx.sentTs = proposal.sentTs;
// tx.merchant = proposal.merchant;
//tx.paymentAckMemo = proposal.paymentAckMemo;
}
});
};
2015-02-21 19:12:05 -08:00
function paginate(txs) {
// TODO
};
2015-02-21 17:35:12 -08:00
// Get addresses for this wallet
self.storage.fetchAddresses(self.walletId, function(err, addresses) {
if (err) return cb(err);
if (addresses.length == 0) return cb(null, []);
var addressStrs = _.pluck(addresses, 'address');
var networkName = Bitcore.Address(addressStrs[0]).toObject().network;
var bc = self._getBlockExplorer('insight', networkName);
async.parallel([
function(next) {
self.storage.fetchTxs(self.walletId, opts, function(err, txps) {
if (err) return next(err);
next(null, txps);
});
},
function(next) {
bc.getTransactions(addressStrs, function(err, txs) {
if (err) return next(err);
next(null, self._normalizeTxHistory(txs));
});
},
], function(err, res) {
if (err) return cb(err);
var proposals = res[0];
var txs = res[1];
decorate(txs, addresses, proposals);
2015-02-21 19:12:05 -08:00
paginate(txs);
2015-02-21 17:35:12 -08:00
return cb(null, txs);
});
});
};
2015-02-11 18:13:19 -08:00
2015-02-06 23:09:45 -08:00
2015-02-20 12:32:19 -08:00
module.exports = WalletService;
2015-02-09 10:30:16 -08:00
module.exports.ClientError = ClientError;