bitcore-wallet-service/lib/server.js

1935 lines
55 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-04-18 02:55:24 -07:00
log.disableColor();
var EmailValidator = require('email-validator');
2015-02-02 10:29:14 -08:00
2015-03-12 07:34:41 -07:00
var WalletUtils = require('bitcore-wallet-utils');
var Bitcore = WalletUtils.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 05:18:45 -08:00
2015-07-31 08:16:18 -07:00
var ClientError = require('./errors/clienterror');
var Errors = require('./errors/errordefinitions');
2015-02-02 11:00:32 -08:00
var Utils = require('./utils');
2015-04-07 13:02:08 -07:00
var Lock = require('./lock');
2015-01-27 05:18:45 -08:00
var Storage = require('./storage');
2015-05-06 06:00:09 -07:00
var MessageBroker = require('./messagebroker');
2015-03-30 16:16:51 -07:00
var BlockchainExplorer = require('./blockchainexplorer');
2015-01-27 11:40:21 -08:00
2015-04-27 11:38:33 -07:00
var Model = require('./model');
var Wallet = Model.Wallet;
2015-01-27 05:18:45 -08:00
2015-02-06 12:56:51 -08:00
var initialized = false;
2015-04-28 20:34:18 -07:00
var lock;
var storage;
var blockchainExplorer;
var blockchainExplorerOpts;
2015-05-06 06:00:09 -07:00
var messageBroker;
2015-02-06 12:56:51 -08:00
2015-08-05 12:53:06 -07:00
var MAX_KEYS = 100;
2015-06-11 12:39:21 -07:00
2015-01-27 07:54:17 -08:00
/**
2015-03-04 09:04:34 -08:00
* Creates an instance of the Bitcore Wallet Service.
2015-01-27 07:54:17 -08:00
* @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-04-07 13:02:08 -07:00
this.lock = lock;
2015-02-06 12:56:51 -08:00
this.storage = storage;
2015-03-30 16:16:51 -07:00
this.blockchainExplorer = blockchainExplorer;
2015-04-15 06:59:25 -07:00
this.blockchainExplorerOpts = blockchainExplorerOpts;
2015-05-06 06:00:09 -07:00
this.messageBroker = messageBroker;
2015-02-12 05:26:13 -08:00
this.notifyTicker = 0;
2015-02-06 12:56:51 -08:00
};
2015-06-12 12:05:33 -07:00
// Time after which a Tx proposal can be erased by any copayer. in seconds
2015-08-13 13:24:49 -07:00
WalletService.DELETE_LOCKTIME = 24 * 3600;
2015-06-12 12:05:33 -07:00
// Allowed consecutive txp rejections before backoff is applied.
2015-08-13 13:24:49 -07:00
WalletService.BACKOFF_OFFSET = 3;
// Time a copayer need to wait to create a new TX after her tx previous proposal we rejected. (incremental). in Minutes.
2015-08-13 13:24:49 -07:00
WalletService.BACKOFF_TIME = 2;
2015-06-12 12:05:33 -07:00
// Fund scanning parameters
2015-08-13 13:24:49 -07:00
WalletService.SCAN_CONFIG = {
scanWindow: 20,
derivationDelay: 10, // in milliseconds
2015-06-12 12:05:33 -07:00
};
2015-08-13 13:24:49 -07:00
WalletService.FEE_LEVELS = [{
name: 'priority',
nbBlocks: 1,
defaultValue: 50000
}, {
name: 'normal',
2015-08-13 13:27:06 -07:00
nbBlocks: 2,
2015-08-13 13:24:49 -07:00
defaultValue: 20000
}, {
name: 'economy',
2015-08-13 13:27:06 -07:00
nbBlocks: 6,
2015-08-13 13:24:49 -07:00
defaultValue: 10000
}];
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-03-30 16:16:51 -07:00
* @param {Storage} [opts.blockchainExplorer] - The blockchainExporer provider.
2015-04-21 10:43:35 -07:00
* @param {Callback} cb
2015-01-27 07:54:17 -08:00
*/
2015-04-21 10:43:35 -07:00
WalletService.initialize = function(opts, cb) {
$.shouldBeFunction(cb);
2015-02-02 12:07:18 -08:00
opts = opts || {};
2015-04-07 13:02:08 -07:00
lock = opts.lock || new Lock(opts.lockOpts);
2015-03-30 16:16:51 -07:00
blockchainExplorer = opts.blockchainExplorer;
2015-04-15 06:59:25 -07:00
blockchainExplorerOpts = opts.blockchainExplorerOpts;
2015-04-21 10:43:35 -07:00
2015-05-04 14:23:56 -07:00
function initStorage(cb) {
if (opts.storage) {
storage = opts.storage;
return cb();
2015-04-28 20:34:18 -07:00
} else {
var newStorage = new Storage();
newStorage.connect(opts.storageOpts, function(err) {
if (err) return cb(err);
storage = newStorage;
return cb();
});
2015-05-04 14:23:56 -07:00
}
2015-04-28 20:34:18 -07:00
};
2015-05-06 06:00:09 -07:00
function initMessageBroker(cb) {
if (opts.messageBroker) {
messageBroker = opts.messageBroker;
} else {
messageBroker = new MessageBroker(opts.messageBrokerOpts);
2015-05-04 14:23:56 -07:00
}
2015-05-05 09:04:29 -07:00
return cb();
2015-05-04 14:23:56 -07:00
};
async.series([
function(next) {
initStorage(next);
},
function(next) {
2015-05-06 06:00:09 -07:00
initMessageBroker(next);
2015-05-04 14:23:56 -07:00
},
], function(err) {
if (err) {
log.error('Could not initialize', err);
throw err;
}
initialized = true;
return cb();
});
2015-04-21 10:43:35 -07:00
};
WalletService.shutDown = function(cb) {
2015-04-23 08:25:36 -07:00
if (!initialized) return cb();
storage.disconnect(function(err) {
if (err) return cb(err);
initialized = false;
return cb();
});
2015-01-27 05:18:45 -08:00
};
2015-06-29 08:20:24 -07:00
/**
* Gets an instance of the server without authentication.
* @param {Object} opts
* @param {string} opts.clientVersion - A string that identifies the client issuing the request
*/
WalletService.getInstance = function(opts) {
opts = opts || {};
var server = new WalletService();
server.clientVersion = opts.clientVersion;
return server;
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-08-04 17:05:26 -07:00
* @param {string} opts.signature - Signature of message to be verified using one of the copayer's requestPubKeys
2015-06-29 08:20:24 -07:00
* @param {string} opts.clientVersion - A string that identifies the client issuing the request
2015-02-06 12:56:51 -08:00
*/
2015-02-20 12:32:19 -08:00
WalletService.getInstanceWithAuth = function(opts, cb) {
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-08-03 12:11:09 -07:00
if (!copayer) return cb(new ClientError(Errors.codes.NOT_AUTHORIZED, 'Copayer not found'));
2015-02-06 12:56:51 -08:00
2015-08-05 12:53:06 -07:00
var isValid = !!server._getSigningKey(opts.message, opts.signature, copayer.requestPubKeys);
2015-02-21 14:29:42 -08:00
if (!isValid)
2015-08-03 12:11:09 -07:00
return cb(new ClientError(Errors.codes.NOT_AUTHORIZED, '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;
2015-06-29 04:41:59 -07:00
server.clientVersion = opts.clientVersion;
2015-02-06 12:56:51 -08:00
return cb(null, server);
});
2015-02-02 10:56:53 -08:00
};
2015-01-27 05:18:45 -08:00
2015-04-08 11:18:28 -07:00
WalletService.prototype._runLocked = function(cb, task) {
$.checkState(this.walletId);
this.lock.runLocked(this.walletId, cb, task);
};
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-09-04 17:05:39 -07:00
* @param {string} [opts.supportBIP44 = false] - Client supports BIP44 paths for 1-of-1 wallets.
2015-09-04 20:50:51 -07:00
* @param {string} [opts.supportP2PKH = false] - Client supports P2PKH address type for 1-of-1 wallets.
2015-01-27 07:54:17 -08:00
*/
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-08-28 10:54:36 -07:00
opts.network = opts.network || 'livenet';
if (!_.contains(['livenet', 'testnet'], opts.network))
2015-02-07 08:13:29 -08:00
return cb(new ClientError('Invalid network'));
2015-02-02 10:29:14 -08:00
2015-09-04 17:05:39 -07:00
var derivationStrategy = (opts.n == 1 && opts.supportBIP44) ?
WalletUtils.DERIVATION_STRATEGIES.BIP44 : WalletUtils.DERIVATION_STRATEGIES.BIP45;
2015-08-28 10:54:36 -07:00
2015-09-04 20:50:51 -07:00
var addressType = (opts.n == 1 && opts.supportP2PKH) ?
WalletUtils.SCRIPT_TYPES.P2PKH : WalletUtils.SCRIPT_TYPES.P2SH;
2015-01-31 14:56:50 -08:00
try {
pubKey = new PublicKey.fromString(opts.pubKey);
2015-02-24 05:36:14 -08:00
} catch (ex) {
return cb(new ClientError('Invalid public key'));
2015-01-31 14:56:50 -08:00
};
2015-01-30 06:58:28 -08:00
2015-03-31 13:28:01 -07:00
var newWallet;
async.series([
function(acb) {
if (!opts.id)
return acb();
2015-02-07 08:13:29 -08:00
2015-03-31 13:28:01 -07:00
self.storage.fetchWallet(opts.id, function(err, wallet) {
2015-08-03 12:11:09 -07:00
if (wallet) return acb(Errors.WALLET_ALREADY_EXISTS);
2015-03-31 13:28:01 -07:00
return acb(err);
});
},
function(acb) {
var wallet = Wallet.create({
2015-08-28 10:54:36 -07:00
id: opts.id,
2015-03-31 13:28:01 -07:00
name: opts.name,
m: opts.m,
n: opts.n,
2015-08-28 10:54:36 -07:00
network: opts.network,
2015-03-31 13:28:01 -07:00
pubKey: pubKey.toString(),
2015-09-04 17:05:39 -07:00
derivationStrategy: derivationStrategy,
2015-09-04 20:50:51 -07:00
addressType: addressType,
2015-03-31 13:28:01 -07:00
});
self.storage.storeWallet(wallet, function(err) {
2015-08-28 10:54:36 -07:00
log.debug('Wallet created', wallet.id, opts.network);
2015-03-31 13:28:01 -07:00
newWallet = wallet;
return acb(err);
});
}
], function(err) {
return cb(err, newWallet ? newWallet.id : null);
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-08-05 06:41:03 -07:00
if (!wallet) return cb(Errors.WALLET_NOT_FOUND);
2015-02-02 12:07:18 -08:00
return cb(null, wallet);
});
2015-01-27 05:18:45 -08:00
};
2015-08-18 13:56:46 -07:00
/**
* Retrieves wallet status.
* @param {Object} opts
2015-08-18 14:22:43 -07:00
* @param {Object} opts.includeExtendedInfo - Include PKR info & address managers for wallet & copayers
2015-08-18 13:56:46 -07:00
* @returns {Object} status
*/
WalletService.prototype.getStatus = function(opts, cb) {
var self = this;
2015-08-18 14:22:43 -07:00
opts = opts || {};
2015-08-18 13:56:46 -07:00
var status = {};
async.parallel([
function(next) {
self.getWallet({}, function(err, wallet) {
if (err) return next(err);
2015-08-18 14:22:43 -07:00
var walletExtendedKeys = ['publicKeyRing', 'pubKey', 'addressManager'];
2015-08-25 12:12:47 -07:00
var copayerExtendedKeys = ['xPubKey', 'requestPubKey', 'signature', 'addressManager', 'customData'];
2015-08-18 14:22:43 -07:00
2015-08-25 12:12:47 -07:00
wallet.copayers = _.map(wallet.copayers, function(copayer) {
if (copayer.id == self.copayerId) return copayer;
return _.omit(copayer, 'customData');
});
2015-08-18 14:22:43 -07:00
if (!opts.includeExtendedInfo) {
wallet = _.omit(wallet, walletExtendedKeys);
wallet.copayers = _.map(wallet.copayers, function(copayer) {
return _.omit(copayer, copayerExtendedKeys);
});
}
2015-08-18 13:56:46 -07:00
status.wallet = wallet;
next();
});
},
function(next) {
self.getBalance({}, function(err, balance) {
if (err) return next(err);
status.balance = balance;
next();
});
},
function(next) {
self.getPendingTxs({}, function(err, pendingTxps) {
if (err) return next(err);
status.pendingTxps = pendingTxps;
next();
});
},
function(next) {
self.getPreferences({}, function(err, preferences) {
if (err) return next(err);
status.preferences = preferences;
next();
});
},
], function(err) {
if (err) return cb(err);
return cb(null, status);
});
};
/*
2015-02-01 06:41:16 -08:00
* Verifies a signature
* @param text
* @param signature
2015-08-04 17:05:26 -07:00
* @param pubKeys
2015-02-01 06:41:16 -08:00
*/
2015-08-04 17:05:26 -07:00
WalletService.prototype._verifySignature = function(text, signature, pubkey) {
return WalletUtils.verifyMessage(text, signature, pubkey);
};
/*
* Verifies signature againt a collection of pubkeys
* @param text
* @param signature
* @param pubKeys
*/
2015-08-05 12:53:06 -07:00
WalletService.prototype._getSigningKey = function(text, signature, pubKeys) {
2015-08-04 17:05:26 -07:00
var self = this;
2015-08-05 12:53:06 -07:00
return _.find(pubKeys, function(item) {
2015-08-04 17:05:26 -07:00
return self._verifySignature(text, signature, item.key);
});
2015-02-01 06:41:16 -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
*
2015-04-02 07:57:47 -07:00
* @param {String} type
* @param {Object} data
2015-05-07 10:16:24 -07:00
* @param {Object} opts
* @param {Boolean} opts.isGlobal - If true, the notification is not issued on behalf of any particular copayer (defaults to false)
2015-02-11 11:00:16 -08:00
*/
2015-05-07 10:16:24 -07:00
WalletService.prototype._notify = function(type, data, opts, cb) {
2015-02-11 10:42:49 -08:00
var self = this;
2015-05-07 10:16:24 -07:00
if (_.isFunction(opts)) {
cb = opts;
opts = {};
}
opts = opts || {};
2015-02-12 11:42:32 -08:00
log.debug('Notification', type, data);
2015-04-30 10:50:48 -07:00
cb = cb || function() {};
2015-02-11 18:11:30 -08:00
var walletId = self.walletId || data.walletId;
var copayerId = self.copayerId || data.copayerId;
2015-02-11 18:11:30 -08:00
$.checkState(walletId);
2015-04-28 08:49:43 -07:00
var notification = Model.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-05-07 10:16:24 -07:00
creatorId: opts.isGlobal ? null : copayerId,
2015-03-30 07:24:33 -07:00
walletId: walletId,
2015-02-11 10:42:49 -08:00
});
2015-04-28 20:34:18 -07:00
this.storage.storeNotification(walletId, notification, function() {
self.messageBroker.send(notification);
2015-05-29 06:30:59 -07:00
return cb();
2015-02-11 10:42:49 -08:00
});
};
2015-04-28 08:49:43 -07:00
2015-08-05 12:53:06 -07:00
WalletService.prototype._addCopayerToWallet = function(wallet, opts, cb) {
var self = this;
if (wallet.copayers.length == wallet.n) return cb(Errors.WALLET_FULL);
var copayer = Model.Copayer.create({
name: opts.name,
copayerIndex: wallet.copayers.length,
xPubKey: opts.xPubKey,
requestPubKey: opts.requestPubKey,
signature: opts.copayerSignature,
2015-08-25 12:12:47 -07:00
customData: opts.customData,
2015-09-04 17:05:39 -07:00
derivationStrategy: wallet.derivationStrategy,
2015-08-05 12:53:06 -07:00
});
self.storage.fetchCopayerLookup(copayer.id, function(err, res) {
if (err) return cb(err);
if (res) return cb(Errors.COPAYER_REGISTERED);
wallet.addCopayer(copayer);
self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) {
if (err) return cb(err);
async.series([
function(next) {
self._notify('NewCopayer', {
walletId: opts.walletId,
copayerId: copayer.id,
copayerName: copayer.name,
}, next);
},
function(next) {
if (wallet.isComplete() && wallet.isShared()) {
self._notify('WalletComplete', {
walletId: opts.walletId,
}, {
isGlobal: true
}, next);
} else {
next();
}
},
], function() {
return cb(null, {
copayerId: copayer.id,
wallet: wallet
});
});
});
});
};
WalletService.prototype._addKeyToCopayer = function(wallet, copayer, opts, cb) {
var self = this;
2015-08-10 11:07:20 -07:00
wallet.addCopayerRequestKey(copayer.copayerId, opts.requestPubKey, opts.signature, opts.restrictions, opts.name);
2015-08-05 12:53:06 -07:00
self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) {
if (err) return cb(err);
return cb(null, {
copayerId: copayer.id,
wallet: wallet
});
});
};
/**
* Adds access to a given copayer
*
* @param {Object} opts
* @param {string} opts.copayerId - The copayer id
* @param {string} opts.requestPubKey - Public Key used to check requests from this copayer.
* @param {string} opts.copayerSignature - S(requestPubKey). Used by other copayers to verify the that the copayer is himself (signed with REQUEST_KEY_AUTH)
* @param {string} opts.restrictions
* - cannotProposeTXs
* - cannotXXX TODO
2015-08-10 11:07:20 -07:00
* @param {string} opts.name (name for the new access)
2015-08-05 12:53:06 -07:00
*/
WalletService.prototype.addAccess = function(opts, cb) {
var self = this;
if (!Utils.checkRequired(opts, ['copayerId', 'requestPubKey', 'signature']))
return cb(new ClientError('Required argument missing'));
self.storage.fetchCopayerLookup(opts.copayerId, function(err, copayer) {
if (err) return cb(err);
if (!copayer) return cb(Errors.NOT_AUTHORIZED);
self.storage.fetchWallet(copayer.walletId, function(err, wallet) {
if (err) return cb(err);
if (!wallet) return cb(Errors.NOT_AUTHORIZED);
var xPubKey = _.find(wallet.copayers, {
id: opts.copayerId
}).xPubKey;
2015-08-10 11:07:20 -07:00
if (!WalletUtils.verifyRequestPubKey(opts.requestPubKey, opts.signature, xPubKey)) {
2015-08-05 12:53:06 -07:00
return cb(Errors.NOT_AUTHORIZED);
}
if (copayer.requestPubKeys.length > MAX_KEYS)
2015-08-14 08:51:48 -07:00
return cb(Errors.TOO_MANY_KEYS);
2015-08-05 12:53:06 -07:00
self._addKeyToCopayer(wallet, copayer, opts, cb);
});
});
};
2015-09-01 07:53:07 -07:00
WalletService.prototype._parseClientVersion = function() {
function parse(version) {
var v = {};
if (!version) return null;
var x = version.split('-');
if (x.length != 2) {
v.agent = version;
return v;
}
v.agent = _.contains(['bwc', 'bws'], x[0]) ? 'bwc' : x[0];
x = x[1].split('.');
v.major = parseInt(x[0]);
v.minor = parseInt(x[1]);
v.patch = parseInt(x[2]);
return v;
};
if (_.isUndefined(this.parsedClientVersion)) {
this.parsedClientVersion = parse(this.clientVersion);
}
return this.parsedClientVersion;
};
WalletService.prototype._clientSupportsTXPv2 = function() {
var version = this._parseClientVersion();
if (!version) return false;
if (version.agent != 'bwc') return true; // Asume 3rd party clients are up-to-date
if (version.major == 0 && version.minor == 0) return false;
return true;
};
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.
2015-03-09 14:11:25 -07:00
* @param {string} opts.xPubKey - Extended Public Key for this copayer.
* @param {string} opts.requestPubKey - Public Key used to check requests from this copayer.
2015-08-25 12:12:47 -07:00
* @param {string} opts.copayerSignature - S(name|xPubKey|requestPubKey). Used by other copayers to verify that the copayer joining knows the wallet secret.
* @param {string} opts.customData - (optional) Custom data for this copayer.
2015-01-27 07:54:17 -08:00
*/
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-03-10 07:23:23 -07:00
if (!Utils.checkRequired(opts, ['walletId', 'name', 'xPubKey', 'requestPubKey', 'copayerSignature']))
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-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-04-08 11:18:28 -07:00
self.walletId = opts.walletId;
self._runLocked(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-08-05 06:41:03 -07:00
if (!wallet) return cb(Errors.WALLET_NOT_FOUND);
2015-02-01 06:41:16 -08:00
2015-03-10 07:23:23 -07:00
var hash = WalletUtils.getCopayerHash(opts.name, opts.xPubKey, opts.requestPubKey);
if (!self._verifySignature(hash, opts.copayerSignature, 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-08-03 12:11:09 -07:00
})) return cb(Errors.COPAYER_IN_WALLET);
2015-02-17 12:36:45 -08:00
2015-08-05 12:53:06 -07:00
self._addCopayerToWallet(wallet, opts, cb);
2015-02-02 12:07:18 -08:00
});
});
2015-01-27 05:18:45 -08:00
};
2015-04-27 11:38:33 -07:00
/**
* Save copayer preferences for the current wallet/copayer pair.
* @param {Object} opts
* @param {string} opts.email - Email address for notifications.
* @param {string} opts.language - Language used for notifications.
* @param {string} opts.unit - Bitcoin unit used to format amounts in notifications.
2015-04-27 11:38:33 -07:00
*/
WalletService.prototype.savePreferences = function(opts, cb) {
var self = this;
opts = opts || {};
var preferences = [{
name: 'email',
isValid: function(value) {
return EmailValidator.validate(value);
},
}, {
name: 'language',
isValid: function(value) {
return _.isString(value) && value.length == 2;
},
}, {
name: 'unit',
isValid: function(value) {
return _.isString(value) && _.contains(['btc', 'bit'], value.toLowerCase());
},
}];
2015-06-29 04:57:53 -07:00
opts = _.pick(opts, _.pluck(preferences, 'name'));
try {
_.each(preferences, function(preference) {
var value = opts[preference.name];
if (!value) return;
if (!preference.isValid(value)) {
throw 'Invalid ' + preference.name;
return false;
}
});
} catch (ex) {
return cb(new ClientError(ex));
2015-05-11 07:46:28 -07:00
}
2015-04-27 11:38:33 -07:00
self._runLocked(cb, function(cb) {
self.storage.fetchPreferences(self.walletId, self.copayerId, function(err, oldPref) {
if (err) return cb(err);
var newPref = Model.Preferences.create({
walletId: self.walletId,
copayerId: self.copayerId,
});
var preferences = Model.Preferences.fromObj(_.defaults(newPref, opts, oldPref));
self.storage.storePreferences(preferences, function(err) {
return cb(err);
});
2015-04-27 11:38:33 -07:00
});
});
};
/**
* Retrieves a preferences for the current wallet/copayer pair.
* @param {Object} opts
* @returns {Object} preferences
*/
WalletService.prototype.getPreferences = function(opts, cb) {
var self = this;
self.storage.fetchPreferences(self.walletId, self.copayerId, function(err, preferences) {
if (err) return cb(err);
return cb(null, preferences || {});
});
};
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-04-08 11:18:28 -07:00
self._runLocked(cb, function(cb) {
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-08-05 06:44:09 -07:00
if (!wallet.isComplete()) return cb(Errors.WALLET_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-03-30 08:45:43 -07:00
self._notify('NewAddress', {
address: address.address,
2015-05-07 10:16:24 -07:00
}, function() {
2015-04-30 16:31:45 -07:00
return cb(null, address);
2015-03-30 08:45:43 -07:00
});
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-08-05 12:53:06 -07:00
var isValid = !!self._getSigningKey(opts.message, opts.signature, copayer.requestPubKeys);
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-07-15 18:42:05 -07:00
WalletService.prototype._getBlockchainExplorer = function(network) {
2015-03-30 16:16:51 -07:00
if (!this.blockchainExplorer) {
2015-04-17 14:25:41 -07:00
var opts = {};
2015-04-15 06:59:25 -07:00
if (this.blockchainExplorerOpts && this.blockchainExplorerOpts[network]) {
2015-04-17 14:25:41 -07:00
opts = this.blockchainExplorerOpts[network];
2015-04-15 06:59:25 -07:00
}
2015-07-15 18:42:05 -07:00
// TODO: provider should be configurable
opts.provider = 'insight';
2015-04-15 06:59:25 -07:00
opts.network = network;
this.blockchainExplorer = new BlockchainExplorer(opts);
2015-02-02 12:07:18 -08:00
}
2015-03-30 11:34:05 -07:00
2015-03-30 16:16:51 -07:00
return this.blockchainExplorer;
2015-01-27 05:18:45 -08:00
};
2015-08-13 08:01:22 -07:00
WalletService.prototype._getUtxosForAddresses = function(addresses, cb) {
2015-02-02 12:07:18 -08:00
var self = this;
2015-08-13 08:01:22 -07:00
if (addresses.length == 0) return cb(null, []);
var networkName = Bitcore.Address(addresses[0]).toObject().network;
var bc = self._getBlockchainExplorer(networkName);
bc.getUnspentUtxos(addresses, function(err, utxos) {
if (err) return cb(err);
var utxos = _.map(utxos, function(utxo) {
var u = _.pick(utxo, ['txid', 'vout', 'address', 'scriptPubKey', 'amount', 'satoshis', 'confirmations']);
u.confirmations = u.confirmations || 0;
u.locked = false;
u.satoshis = u.satoshis ? +u.satoshis : Utils.strip(u.amount * 1e8);
delete u.amount;
return u;
});
return cb(null, utxos);
});
};
WalletService.prototype._getUtxosForCurrentWallet = function(cb) {
var self = this;
2015-08-13 07:00:27 -07:00
2015-07-20 09:44:39 -07:00
function utxoKey(utxo) {
return utxo.txid + '|' + utxo.vout
};
2015-02-02 12:07:18 -08:00
// 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-04 06:43:12 -08:00
var addressStrs = _.pluck(addresses, 'address');
2015-08-13 08:01:22 -07:00
self._getUtxosForAddresses(addressStrs, function(err, utxos) {
2015-08-02 15:48:18 -07:00
if (err) return cb(err);
2015-08-13 08:01:22 -07:00
if (utxos.length == 0) return cb(null, []);
2015-08-02 15:48:18 -07: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-07-20 09:44:39 -07:00
var lockedInputs = _.map(_.flatten(_.pluck(txps, 'inputs')), utxoKey);
var utxoIndex = _.indexBy(utxos, utxoKey);
_.each(lockedInputs, function(input) {
if (utxoIndex[input]) {
utxoIndex[input].locked = true;
2015-02-02 12:07:18 -08:00
}
});
2015-02-03 18:17:06 -08:00
2015-02-04 06:43:12 -08:00
// Needed for the clients to sign UTXOs
2015-08-13 08:01:22 -07:00
var addressToPath = _.indexBy(addresses, 'address');
2015-02-04 06:43:12 -08:00
_.each(utxos, function(utxo) {
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-08-13 08:01:22 -07:00
/**
* Returns list of UTXOs
* @param {Object} opts
* @param {Array} opts.addresses (optional) - List of addresses from where to fetch UTXOs.
* @returns {Array} utxos - List of UTXOs.
*/
WalletService.prototype.getUtxos = function(opts, cb) {
var self = this;
opts = opts || {};
if (_.isUndefined(opts.addresses)) {
self._getUtxosForCurrentWallet(cb);
} else {
self._getUtxosForAddresses(opts.addresses, cb);
}
};
WalletService.prototype._totalizeUtxos = function(utxos) {
2015-07-20 08:45:12 -07:00
var balance = {
totalAmount: _.sum(utxos, 'satoshis'),
lockedAmount: _.sum(_.filter(utxos, 'locked'), 'satoshis'),
totalConfirmedAmount: _.sum(_.filter(utxos, 'confirmations'), 'satoshis'),
lockedConfirmedAmount: _.sum(_.filter(_.filter(utxos, 'locked'), 'confirmations'), 'satoshis'),
2015-07-20 08:45:12 -07:00
};
balance.availableAmount = balance.totalAmount - balance.lockedAmount;
balance.availableConfirmedAmount = balance.totalConfirmedAmount - balance.lockedConfirmedAmount;
return balance;
};
2015-01-30 12:37:30 -08:00
2015-07-27 08:19:27 -07:00
WalletService.prototype._computeBytesToSendMax = function(utxos, cb) {
2015-06-18 09:31:53 -07:00
var self = this;
2015-07-20 09:44:39 -07:00
var unlockedUtxos = _.reject(utxos, 'locked');
2015-06-18 09:31:53 -07:00
if (_.isEmpty(unlockedUtxos)) return cb(null, 0);
self.getWallet({}, function(err, wallet) {
if (err) return cb(err);
2015-07-27 08:19:27 -07:00
var txp = Model.TxProposal.create({
walletId: self.walletId,
requiredSignatures: wallet.m,
walletN: wallet.n,
});
txp.inputs = unlockedUtxos;
var size = txp.getEstimatedSize();
return cb(null, size);
2015-06-18 09:31:53 -07: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-08-13 07:00:27 -07:00
self.getUtxos({}, function(err, utxos) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
var balance = self._totalizeUtxos(utxos);
2015-01-30 12:37:30 -08:00
2015-03-06 09:58:22 -08:00
// Compute balance by address
var byAddress = {};
_.each(_.indexBy(utxos, 'address'), function(value, key) {
byAddress[key] = {
address: key,
path: value.path,
amount: 0,
};
});
_.each(utxos, function(utxo) {
byAddress[utxo.address].amount += utxo.satoshis;
});
balance.byAddress = _.values(byAddress);
2015-07-27 08:38:12 -07:00
self._computeBytesToSendMax(utxos, function(err, size) {
2015-06-18 09:31:53 -07:00
if (err) {
log.error('Could not compute fees needed to transfer max amount', err);
}
2015-07-27 08:38:12 -07:00
balance.totalBytesToSendMax = size || 0;
return cb(null, balance);
});
2015-02-02 12:07:18 -08:00
});
2015-01-30 12:37:30 -08:00
};
2015-07-15 18:42:05 -07:00
WalletService.prototype._sampleFeeLevels = function(network, points, cb) {
var self = this;
2015-07-15 18:44:34 -07:00
var bc = self._getBlockchainExplorer(network);
2015-08-12 14:39:19 -07:00
bc.estimateFee(points, function(err, result) {
if (err) {
log.error('Error estimating fee', err);
return cb(err);
}
var levels = _.zipObject(_.map(points, function(p) {
var feePerKB = _.isObject(result) ? +result[p] : -1;
2015-07-17 06:32:48 -07:00
if (feePerKB < 0) {
log.warn('Could not compute fee estimation (nbBlocks=' + p + ')');
}
2015-08-12 14:39:19 -07:00
return [p, Utils.strip(feePerKB * 1e8)];
}));
return cb(null, levels);
2015-07-15 18:42:05 -07:00
});
};
/**
* Returns fee levels for the current state of the network.
* @param {Object} opts
* @param {string} [opts.network = 'livenet'] - The Bitcoin network to estimate fee levels from.
* @returns {Object} feeLevels - A list of fee levels & associated amount per kB in satoshi.
*/
WalletService.prototype.getFeeLevels = function(opts, cb) {
var self = this;
opts = opts || {};
var network = opts.network || 'livenet';
if (network != 'livenet' && network != 'testnet')
return cb(new ClientError('Invalid network'));
2015-08-13 13:24:49 -07:00
var levels = WalletService.FEE_LEVELS;
2015-07-15 18:42:05 -07:00
var samplePoints = _.uniq(_.pluck(levels, 'nbBlocks'));
self._sampleFeeLevels(network, samplePoints, function(err, feeSamples) {
2015-07-16 12:17:58 -07:00
var values = _.map(levels, function(level) {
2015-07-27 05:00:37 -07:00
var result = {
2015-07-16 12:17:58 -07:00
level: level.name,
};
if (err || feeSamples[level.nbBlocks] < 0) {
result.feePerKB = level.defaultValue;
result.nbBlocks = null;
} else {
result.feePerKB = feeSamples[level.nbBlocks];
result.nbBlocks = level.nbBlocks;
}
return result;
2015-07-16 12:17:58 -07:00
});
2015-07-15 18:42:05 -07:00
return cb(null, values);
});
};
WalletService.prototype._selectTxInputs = function(txp, utxosToExclude, cb) {
2015-03-11 11:04:42 -07:00
var self = this;
2015-01-30 12:37:30 -08:00
2015-07-16 08:55:59 -07:00
function sortUtxos(utxos) {
var list = _.map(utxos, function(utxo) {
var order;
2015-07-16 11:17:03 -07:00
if (utxo.confirmations == 0) {
order = 0;
2015-07-16 11:17:03 -07:00
} else if (utxo.confirmations < 6) {
order = -1;
2015-07-16 08:55:59 -07:00
} else {
order = -2;
2015-07-16 08:55:59 -07:00
}
return {
order: order,
utxo: utxo
};
2015-07-16 08:55:59 -07:00
});
return _.pluck(_.sortBy(list, 'order'), 'utxo');
2015-07-16 08:55:59 -07:00
};
2015-08-13 07:00:27 -07:00
self.getUtxos({}, function(err, utxos) {
2015-03-11 11:04:42 -07:00
if (err) return cb(err);
2015-08-27 13:14:33 -07:00
var excludeIndex = _.reduce(utxosToExclude, function(res, val) {
res[val] = val;
return res;
}, {});
utxos = _.reject(utxos, function(utxo) {
return excludeIndex[utxo.txid + ":" + utxo.vout];
});
var totalAmount;
var availableAmount;
var balance = self._totalizeUtxos(utxos);
if (txp.excludeUnconfirmedUtxos) {
totalAmount = balance.totalConfirmedAmount;
availableAmount = balance.availableConfirmedAmount;
} else {
totalAmount = balance.totalAmount;
availableAmount = balance.availableAmount;
}
2015-08-03 12:11:09 -07:00
if (totalAmount < txp.getTotalAmount()) return cb(Errors.INSUFFICIENT_FUNDS);
if (availableAmount < txp.amount) return cb(Errors.LOCKED_FUNDS);
// Prepare UTXOs list
utxos = _.reject(utxos, 'locked');
if (txp.excludeUnconfirmedUtxos) {
utxos = _.filter(utxos, 'confirmations');
}
2015-02-04 11:18:36 -08:00
2015-03-11 11:04:42 -07:00
var i = 0;
var total = 0;
var selected = [];
2015-07-16 08:55:59 -07:00
var inputs = sortUtxos(utxos);
2015-03-25 08:17:41 -07:00
var bitcoreTx, bitcoreError;
2015-07-29 14:19:53 -07:00
var serializationOpts = {
disableIsFullySigned: true,
};
if (!_.startsWith(txp.version, '1.')) {
serializationOpts.disableSmallFees = true;
serializationOpts.disableLargeFees = true;
}
2015-03-11 11:04:42 -07:00
while (i < inputs.length) {
selected.push(inputs[i]);
total += inputs[i].satoshis;
2015-03-25 08:17:41 -07:00
i++;
2015-03-11 11:04:42 -07:00
if (total >= txp.getTotalAmount()) {
2015-03-11 11:04:42 -07:00
try {
txp.setInputs(selected);
2015-07-27 05:00:37 -07:00
txp.estimateFee();
bitcoreTx = txp.getBitcoreTx();
2015-07-29 14:19:53 -07:00
bitcoreError = bitcoreTx.getSerializationError(serializationOpts);
2015-03-25 08:17:41 -07:00
if (!bitcoreError) {
txp.fee = bitcoreTx.getFee();
return cb();
2015-03-11 11:04:42 -07:00
}
2015-03-25 08:17:41 -07:00
} catch (ex) {
2015-06-16 14:05:26 -07:00
log.error('Error building Bitcore transaction', ex);
2015-03-25 08:17:41 -07:00
return cb(ex);
2015-02-16 10:00:41 -08:00
}
2015-02-16 09:27:01 -08:00
}
}
2015-07-31 08:16:18 -07:00
if (bitcoreError instanceof Bitcore.errors.Transaction.FeeError)
2015-08-03 12:11:09 -07:00
return cb(Errors.INSUFFICIENT_FUNDS_FOR_FEE);
2015-07-31 08:16:18 -07:00
if (bitcoreError instanceof Bitcore.errors.Transaction.DustOutputs)
2015-08-03 12:11:09 -07:00
return cb(Errors.DUST_AMOUNT);
2015-03-25 08:17:41 -07:00
2015-03-25 12:02:31 -07:00
return cb(bitcoreError || new Error('Could not select tx inputs'));
2015-03-11 11:04:42 -07:00
});
2015-01-30 13:29:46 -08:00
};
2015-06-12 12:05:33 -07:00
WalletService.prototype._canCreateTx = function(copayerId, cb) {
var self = this;
2015-08-13 13:24:49 -07:00
self.storage.fetchLastTxs(self.walletId, copayerId, 5 + WalletService.BACKOFF_OFFSET, function(err, txs) {
2015-06-12 12:05:33 -07:00
if (err) return cb(err);
if (!txs.length)
2015-06-12 12:05:33 -07:00
return cb(null, true);
var lastRejections = _.takeWhile(txs, {
status: 'rejected'
});
2015-06-12 12:05:33 -07:00
2015-08-13 13:24:49 -07:00
var exceededRejections = lastRejections.length - WalletService.BACKOFF_OFFSET;
if (exceededRejections <= 0)
2015-06-12 12:05:33 -07:00
return cb(null, true);
2015-06-12 12:05:33 -07:00
var lastTxTs = txs[0].createdOn;
var now = Math.floor(Date.now() / 1000);
var timeSinceLastRejection = now - lastTxTs;
2015-08-13 13:24:49 -07:00
var backoffTime = 60 * Math.pow(WalletService.BACKOFF_TIME, exceededRejections);
2015-06-12 12:05:33 -07:00
if (timeSinceLastRejection <= backoffTime)
log.debug('Not allowing to create TX: timeSinceLastRejection/backoffTime', timeSinceLastRejection, backoffTime);
return cb(null, timeSinceLastRejection > backoffTime);
});
};
2015-01-27 07:54:17 -08:00
/**
* Creates a new transaction proposal.
2015-01-27 11:40:21 -08:00
* @param {Object} opts
* @param {string} opts.type - Proposal type.
* @param {string} opts.toAddress || opts.outputs[].toAddress - Destination address.
* @param {number} opts.amount || opts.outputs[].amount - Amount to transfer in satoshi.
* @param {string} opts.outputs[].message - A message to attach to this output.
2015-01-27 07:54:17 -08:00
* @param {string} opts.message - A message to attach to this transaction.
2015-03-25 12:44:47 -07:00
* @param {string} opts.proposalSignature - S(toAddress|amount|message|payProUrl). Used by other copayers to verify the proposal.
2015-06-11 11:26:34 -07:00
* @param {string} opts.feePerKb - Optional: Use an alternative fee per KB for this TX
* @param {string} opts.payProUrl - Optional: Paypro URL for peers to verify TX
* @param {string} opts.excludeUnconfirmedUtxos - Optional: Do not use UTXOs of unconfirmed transactions as inputs
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-06-25 07:43:47 -07:00
if (!opts.outputs) {
2015-06-25 08:53:53 -07:00
opts.outputs = _.pick(opts, ['amount', 'toAddress']);
2015-06-25 07:43:47 -07:00
}
opts.outputs = [].concat(opts.outputs);
if (!Utils.checkRequired(opts, ['outputs', '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-06-25 08:53:53 -07:00
var type = opts.type || Model.TxProposal.Types.SIMPLE;
if (!Model.TxProposal.isTypeSupported(type))
return cb(new ClientError('Invalid proposal type'));
2015-06-25 07:43:47 -07:00
_.each(opts.outputs, function(output) {
if (!Utils.checkRequired(output, ['toAddress', 'amount'])) {
output.valid = false;
cb(new ClientError('Required outputs argument missing'));
return false;
}
});
if (_.any(opts.outputs, {
valid: false
})) return;
2015-07-27 05:00:37 -07:00
var feePerKb = opts.feePerKb || WalletUtils.DEFAULT_FEE_PER_KB;
2015-06-16 14:05:26 -07:00
if (feePerKb < WalletUtils.MIN_FEE_PER_KB || feePerKb > WalletUtils.MAX_FEE_PER_KB)
2015-06-11 11:26:34 -07:00
return cb(new ClientError('Invalid fee per KB value'));
2015-04-08 11:18:28 -07:00
self._runLocked(cb, function(cb) {
2015-02-08 13:29:58 -08:00
self.getWallet({}, function(err, wallet) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-08-05 06:44:09 -07:00
if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE);
2015-02-24 05:36:14 -08:00
2015-06-25 08:53:53 -07:00
var copayer = wallet.getCopayer(self.copayerId);
var hash;
if (!opts.type || opts.type == Model.TxProposal.Types.SIMPLE) {
2015-06-25 08:53:53 -07:00
hash = WalletUtils.getProposalHash(opts.toAddress, opts.amount, opts.message, opts.payProUrl);
} else {
// should match bwc api _computeProposalSignature
2015-06-25 08:53:53 -07:00
var header = {
outputs: _.map(opts.outputs, function(output) {
return _.pick(output, ['toAddress', 'amount', 'message']);
}),
message: opts.message,
payProUrl: opts.payProUrl
};
hash = WalletUtils.getProposalHash(header)
}
2015-08-05 12:53:06 -07:00
var signingKey = self._getSigningKey(hash, opts.proposalSignature, copayer.requestPubKeys)
if (!signingKey)
2015-06-25 08:53:53 -07:00
return cb(new ClientError('Invalid proposal signature'));
2015-06-12 12:05:33 -07:00
self._canCreateTx(self.copayerId, function(err, canCreate) {
if (err) return cb(err);
2015-08-03 12:11:09 -07:00
if (!canCreate) return cb(Errors.TX_CANNOT_CREATE);
2015-06-25 07:43:47 -07:00
_.each(opts.outputs, function(output) {
output.valid = false;
var toAddress = {};
try {
toAddress = new Bitcore.Address(output.toAddress);
} catch (ex) {
2015-08-04 08:07:25 -07:00
cb(Errors.INVALID_ADDRESS);
return false;
}
if (toAddress.network != wallet.getNetworkName()) {
2015-08-04 08:07:25 -07:00
cb(Errors.INCORRECT_ADDRESS_NETWORK);
return false;
}
2015-06-25 07:43:47 -07:00
if (!_.isNumber(output.amount) || _.isNaN(output.amount) || output.amount <= 0) {
cb(new ClientError('Invalid amount'));
return false;
}
if (output.amount < Bitcore.Transaction.DUST_AMOUNT) {
2015-08-03 12:11:09 -07:00
cb(Errors.DUST_AMOUNT);
return false;
}
output.valid = true;
});
2015-06-25 07:43:47 -07:00
if (_.any(opts.outputs, {
valid: false
})) return;
2015-02-16 10:00:41 -08:00
2015-08-05 12:53:06 -07:00
var txOpts = {
2015-06-25 08:53:53 -07:00
type: type,
2015-06-12 12:05:33 -07:00
walletId: self.walletId,
creatorId: self.copayerId,
outputs: opts.outputs,
2015-06-12 12:05:33 -07:00
toAddress: opts.toAddress,
amount: opts.amount,
message: opts.message,
proposalSignature: opts.proposalSignature,
2015-06-25 08:53:53 -07:00
changeAddress: wallet.createAddress(true),
2015-06-11 11:26:34 -07:00
feePerKb: feePerKb,
2015-06-12 12:05:33 -07:00
payProUrl: opts.payProUrl,
requiredSignatures: wallet.m,
requiredRejections: Math.min(wallet.m, wallet.n - wallet.m + 1),
2015-07-27 05:00:37 -07:00
walletN: wallet.n,
excludeUnconfirmedUtxos: !!opts.excludeUnconfirmedUtxos,
2015-09-04 17:05:39 -07:00
derivationStrategy: wallet.derivationStrategy,
2015-09-05 14:49:43 -07:00
addressType: wallet.addressType,
customData: opts.customData
2015-08-05 12:53:06 -07:00
};
if (signingKey.selfSigned) {
txOpts.proposalSignaturePubKey = signingKey.key;
txOpts.proposalSignaturePubKeySig = signingKey.signature;
}
var txp = Model.TxProposal.create(txOpts);
2015-02-08 13:29:58 -08:00
if (!self._clientSupportsTXPv2()) {
2015-07-29 13:45:25 -07:00
txp.version = '1.0.1';
}
self._selectTxInputs(txp, opts.utxosToExclude, function(err) {
2015-02-08 13:29:58 -08:00
if (err) return cb(err);
2015-01-28 07:06:34 -08:00
2015-06-12 12:05:33 -07:00
$.checkState(txp.inputs);
2015-06-25 07:43:47 -07:00
self.storage.storeAddressAndWallet(wallet, txp.changeAddress, function(err) {
2015-02-08 13:29:58 -08:00
if (err) return cb(err);
2015-06-12 12:05:33 -07:00
self.storage.storeTx(wallet.id, txp, function(err) {
if (err) return cb(err);
self._notify('NewTxProposal', {
amount: txp.getTotalAmount()
2015-06-12 12:05:33 -07:00
}, function() {
return cb(null, txp);
});
2015-02-11 18:11:30 -08:00
});
2015-02-08 15:46:02 -08:00
});
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
2015-02-26 05:41:55 -08:00
* @param {string} opts.txProposalId - The tx id.
2015-02-04 10:45:08 -08:00
* @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-26 05:41:55 -08:00
self.storage.fetchTx(self.walletId, opts.txProposalId, function(err, txp) {
2015-02-04 10:45:08 -08:00
if (err) return cb(err);
2015-08-05 06:48:36 -07:00
if (!txp) return cb(Errors.TX_NOT_FOUND);
2015-02-04 10:45:08 -08:00
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;
2015-04-08 11:18:28 -07:00
self._runLocked(cb, function(cb) {
2015-02-10 11:11:44 -08:00
self.storage.removeWallet(self.walletId, cb);
});
2015-02-09 13:07:15 -08:00
};
2015-06-11 14:38:42 -07:00
WalletService.prototype.getRemainingDeleteLockTime = function(txp) {
var now = Math.floor(Date.now() / 1000);
2015-08-13 13:24:49 -07:00
var lockTimeRemaining = txp.createdOn + WalletService.DELETE_LOCKTIME - now;
2015-06-11 14:38:42 -07:00
if (lockTimeRemaining < 0)
return 0;
// not the creator? need to wait
if (txp.creatorId !== this.copayerId)
return lockTimeRemaining;
// has other approvers? need to wait
var approvers = txp.getApprovers();
if (approvers.length > 1 || (approvers.length == 1 && approvers[0] !== this.copayerId))
return lockTimeRemaining;
2015-06-12 06:06:15 -07:00
2015-06-11 14:38:42 -07:00
return 0;
};
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-04-08 11:18:28 -07:00
self._runLocked(cb, function(cb) {
2015-02-10 11:30:58 -08:00
2015-02-11 07:05:21 -08:00
self.getTx({
2015-02-26 05:41:55 -08:00
txProposalId: 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);
2015-08-03 12:11:09 -07:00
if (!txp.isPending()) return cb(Errors.TX_NOT_PENDING);
2015-02-10 13:04:50 -08:00
2015-06-11 14:38:42 -07:00
var deleteLockTime = self.getRemainingDeleteLockTime(txp);
2015-08-03 12:11:09 -07:00
if (deleteLockTime > 0) return cb(Errors.TX_CANNOT_REMOVE);
2015-07-31 08:16:18 -07:00
2015-06-12 06:06:15 -07:00
self.storage.removeTx(self.walletId, txp.id, function() {
self._notify('TxProposalRemoved', {}, cb);
2015-04-30 16:31:45 -07:00
});
2015-02-10 11:30:58 -08:00
});
});
};
2015-08-13 12:06:22 -07:00
WalletService.prototype._broadcastRawTx = function(network, raw, cb) {
var bc = this._getBlockchainExplorer(network);
2015-02-05 12:22:38 -08:00
bc.broadcast(raw, function(err, txid) {
2015-08-02 15:48:18 -07:00
if (err) return cb(err);
2015-05-15 07:25:54 -07:00
return cb(null, txid);
2015-02-05 12:22:38 -08:00
})
2015-01-28 08:28:18 -08:00
};
2015-08-13 12:06:22 -07:00
/**
* Broadcast a raw transaction.
* @param {Object} opts
* @param {string} [opts.network = 'livenet'] - The Bitcoin network for this transaction.
* @param {string} opts.rawTx - Raw tx data.
*/
WalletService.prototype.broadcastRawTx = function(opts, cb) {
var self = this;
if (!Utils.checkRequired(opts, ['network', 'rawTx']))
return cb(new ClientError('Required argument missing'));
var network = opts.network || 'livenet';
if (network != 'livenet' && network != 'testnet')
return cb(new ClientError('Invalid network'));
self._broadcastRawTx(network, opts.rawTx, cb);
};
2015-05-28 08:51:41 -07:00
WalletService.prototype._checkTxInBlockchain = function(txp, cb) {
var tx = txp.getBitcoreTx();
2015-07-15 18:42:05 -07:00
var bc = this._getBlockchainExplorer(txp.getNetworkName());
2015-05-28 08:51:41 -07:00
bc.getTransaction(tx.id, function(err, tx) {
2015-08-02 15:48:18 -07:00
if (err) return cb(err);
2015-05-28 08:51:41 -07:00
return cb(null, tx);
})
};
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({
2015-02-26 05:41:55 -08:00
txProposalId: opts.txProposalId
2015-02-05 10:50:18 -08:00
}, function(err, txp) {
2015-02-02 12:07:18 -08:00
if (err) return cb(err);
2015-02-10 11:30:58 -08:00
if (!self._clientSupportsTXPv2()) {
if (!_.startsWith(txp.version, '1.')) {
2015-08-11 12:25:29 -07:00
return cb(new ClientError(Errors.codes.UPGRADE_NEEDED, 'To sign this spend proposal you need to upgrade your client app.'));
}
}
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-08-03 12:11:09 -07:00
if (action) return cb(Errors.COPAYER_VOTED);
if (!txp.isPending()) return cb(Errors.TX_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-08-03 12:11:09 -07:00
return cb(Errors.BAD_SIGNATURES);
2015-02-05 10:50:18 -08:00
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-05-14 08:48:19 -07:00
async.series([
2015-04-30 16:31:45 -07:00
2015-05-14 08:48:19 -07:00
function(next) {
2015-04-30 16:31:45 -07:00
self._notify('TxProposalAcceptedBy', {
txProposalId: opts.txProposalId,
copayerId: self.copayerId,
2015-05-14 08:48:19 -07:00
}, next);
2015-04-30 16:31:45 -07:00
},
2015-05-14 08:48:19 -07:00
function(next) {
2015-04-30 16:31:45 -07:00
if (txp.isAccepted()) {
self._notify('TxProposalFinallyAccepted', {
txProposalId: opts.txProposalId,
2015-05-14 08:48:19 -07:00
}, next);
2015-04-30 16:31:45 -07:00
} else {
2015-05-14 08:48:19 -07:00
next();
2015-04-30 16:31:45 -07:00
}
},
], function() {
return cb(null, txp);
2015-02-11 18:11:30 -08:00
});
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'));
2015-05-28 08:51:41 -07:00
function setBroadcasted(txp, txid, cb) {
txp.setBroadcasted(txid);
self.storage.storeTx(self.walletId, txp, function(err) {
if (err) return cb(err);
self._notify('NewOutgoingTx', {
txProposalId: opts.txProposalId,
2015-06-01 08:16:34 -07:00
txid: txid,
amount: txp.getTotalAmount(),
2015-05-28 08:51:41 -07:00
}, function() {
return cb(null, txp);
});
});
};
2015-02-15 13:52:48 -08:00
self.getWallet({}, function(err, wallet) {
if (err) return cb(err);
self.getTx({
2015-02-26 05:41:55 -08:00
txProposalId: opts.txProposalId
2015-02-15 13:52:48 -08:00
}, function(err, txp) {
if (err) return cb(err);
2015-08-03 12:11:09 -07:00
if (txp.status == 'broadcasted') return cb(Errors.TX_ALREADY_BROADCASTED);
if (txp.status != 'accepted') return cb(Errors.TX_NOT_ACCEPTED);
2015-02-15 13:52:48 -08:00
2015-08-13 12:06:22 -07:00
var raw;
try {
raw = txp.getRawTx();
} catch (ex) {
return cb(ex);
}
self._broadcastRawTx(txp.getNetworkName(), raw, function(err, txid) {
2015-05-28 08:51:41 -07:00
if (err) {
var broadcastErr = err;
// Check if tx already in blockchain
self._checkTxInBlockchain(txp, function(err, tx) {
if (err) return cb(err);
if (!tx) return cb(broadcastErr);
2015-02-15 13:52:48 -08:00
2015-05-28 08:51:41 -07:00
setBroadcasted(txp, tx.txid, cb);
2015-02-15 13:52:48 -08:00
});
2015-05-28 08:51:41 -07:00
} else {
setBroadcasted(txp, txid, cb);
}
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({
2015-02-26 05:41:55 -08:00
txProposalId: opts.txProposalId
2015-02-04 11:27:36 -08:00
}, 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
2015-08-03 12:11:09 -07:00
if (action) return cb(Errors.COPAYER_VOTED);
if (txp.status != 'pending') return cb(Errors.TX_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-05-14 08:48:19 -07:00
async.series([
2015-02-11 18:11:30 -08:00
2015-05-14 08:48:19 -07:00
function(next) {
2015-04-30 16:31:45 -07:00
self._notify('TxProposalRejectedBy', {
txProposalId: opts.txProposalId,
copayerId: self.copayerId,
2015-05-14 08:48:19 -07:00
}, next);
2015-04-30 16:31:45 -07:00
},
2015-05-14 08:48:19 -07:00
function(next) {
2015-04-30 16:31:45 -07:00
if (txp.status == 'rejected') {
2015-06-08 14:26:33 -07:00
var rejectedBy = _.pluck(_.filter(txp.actions, {
type: 'reject'
}), 'copayerId');
2015-04-30 16:31:45 -07:00
self._notify('TxProposalFinallyRejected', {
txProposalId: opts.txProposalId,
2015-06-08 14:26:33 -07:00
rejectedBy: rejectedBy,
2015-05-14 08:48:19 -07:00
}, next);
2015-04-30 16:31:45 -07:00
} else {
2015-05-14 08:48:19 -07:00
next();
2015-04-30 16:31:45 -07:00
}
},
], function() {
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-06-12 06:06:15 -07:00
_.each(txps, function(txp) {
2015-06-11 14:38:42 -07:00
txp.deleteLockTime = self.getRemainingDeleteLockTime(txp);
});
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-04-20 15:45:45 -07:00
* @returns {TxProposal[]} Transaction proposals, newer first
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) {
2015-07-20 12:10:08 -07:00
var now = Math.floor(Date.now() / 1000);
2015-02-21 17:35:12 -08:00
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
2015-07-02 08:09:43 -07:00
if (item.scriptPubKey && _.isArray(item.scriptPubKey.addresses) && item.scriptPubKey.addresses.length == 1) {
2015-02-21 17:35:12 -08:00
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-07-20 12:10:08 -07:00
time: tx.firstSeenTs || (!_.isNaN(tx.time) ? tx.time : now) || now,
2015-02-21 17:35:12 -08:00
inputs: inputs,
outputs: outputs,
};
});
};
/**
* Retrieves all transactions (incoming & outgoing)
2015-02-21 17:35:12 -08:00
* Times are in UNIX EPOCH
*
2015-03-17 15:46:01 -07:00
* @param {Object} opts
* @param {Number} opts.skip (defaults to 0)
2015-03-17 15:46:01 -07:00
* @param {Number} opts.limit
2015-02-21 17:35:12 -08:00
* @returns {TxProposal[]} Transaction proposals, first newer
*/
WalletService.prototype.getTxHistory = function(opts, cb) {
var self = this;
function decorate(txs, addresses, proposals) {
var indexedAddresses = _.indexBy(addresses, 'address');
var indexedProposals = _.indexBy(proposals, 'txid');
2015-02-21 17:35:12 -08:00
function sum(items, isMine, isChange) {
var filter = {};
if (_.isBoolean(isMine)) filter.isMine = isMine;
if (_.isBoolean(isChange)) filter.isChange = isChange;
2015-07-20 09:44:39 -07:00
return _.sum(_.filter(items, filter), 'amount');
2015-02-21 17:35:12 -08:00
};
function classify(items) {
return _.map(items, function(item) {
2015-02-21 17:35:12 -08:00
var address = indexedAddresses[item.address];
return {
address: item.address,
amount: item.amount,
isMine: !!address,
isChange: address ? address.isChange : false,
}
2015-02-21 17:35:12 -08:00
});
};
return _.map(txs, function(tx) {
var amountIn, amountOut, amountOutChange;
var amount, action, addressTo;
var inputs, outputs;
2015-07-15 05:57:45 -07:00
if (tx.outputs.length || tx.inputs.length) {
inputs = classify(tx.inputs);
outputs = classify(tx.outputs);
2015-07-15 05:57:45 -07:00
amountIn = sum(inputs, true);
amountOut = sum(outputs, true, false);
amountOutChange = sum(outputs, true, true);
if (amountIn == (amountOut + amountOutChange + (amountIn > 0 ? tx.fees : 0))) {
amount = amountOut;
action = 'moved';
} else {
amount = amountIn - amountOut - amountOutChange - (amountIn > 0 ? tx.fees : 0);
action = amount > 0 ? 'sent' : 'received';
}
amount = Math.abs(amount);
if (action == 'sent' || action == 'moved') {
var firstExternalOutput = _.find(outputs, {
isMine: false
});
addressTo = firstExternalOutput ? firstExternalOutput.address : 'N/A';
};
2015-02-21 17:35:12 -08:00
} else {
2015-07-15 05:57:45 -07:00
action = 'invalid';
amount = 0;
2015-02-21 17:35:12 -08:00
}
2015-07-29 13:45:25 -07:00
function outputMap(o) {
return {
amount: o.amount,
address: o.address
}
};
var newTx = {
txid: tx.txid,
action: action,
amount: amount,
fees: tx.fees,
2015-07-20 12:10:08 -07:00
time: tx.time,
addressTo: addressTo,
2015-07-29 13:45:25 -07:00
outputs: _.map(_.filter(outputs, {
isChange: false
}), outputMap),
confirmations: tx.confirmations,
};
2015-02-21 17:35:12 -08:00
var proposal = indexedProposals[tx.txid];
if (proposal) {
newTx.proposalId = proposal.id;
newTx.proposalType = proposal.type;
newTx.creatorName = proposal.creatorName;
newTx.message = proposal.message;
newTx.actions = _.map(proposal.actions, function(action) {
2015-02-22 18:26:21 -08:00
return _.pick(action, ['createdOn', 'type', 'copayerId', 'copayerName', 'comment']);
});
_.each(newTx.outputs, function(output) {
2015-07-29 13:45:25 -07:00
var query = {
toAddress: output.address,
amount: output.amount
};
var txpOut = _.find(proposal.outputs, query);
output.message = txpOut ? txpOut.message : null;
});
// newTx.sentTs = proposal.sentTs;
// newTx.merchant = proposal.merchant;
//newTx.paymentAckMemo = proposal.paymentAckMemo;
2015-02-21 17:35:12 -08:00
}
return newTx;
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;
2015-07-15 18:42:05 -07:00
var bc = self._getBlockchainExplorer(networkName);
2015-02-21 17:35:12 -08:00
async.parallel([
function(next) {
2015-04-20 12:05:02 -07:00
self.storage.fetchTxs(self.walletId, {}, function(err, txps) {
2015-02-21 17:35:12 -08:00
if (err) return next(err);
next(null, txps);
});
},
function(next) {
2015-07-13 13:32:12 -07:00
var from = opts.skip || 0;
var to = from + (_.isUndefined(opts.limit) ? 100 : opts.limit);
bc.getTransactions(addressStrs, from, to, function(err, txs) {
2015-08-02 15:48:18 -07:00
if (err) return cb(err);
2015-02-21 17:35:12 -08:00
next(null, self._normalizeTxHistory(txs));
});
},
], function(err, res) {
if (err) return cb(err);
var proposals = res[0];
var txs = res[1];
2015-07-13 13:32:12 -07:00
txs = decorate(txs, addresses, proposals);
2015-02-21 17:35:12 -08:00
return cb(null, txs);
});
});
};
2015-02-11 18:13:19 -08:00
2015-04-01 12:42:12 -07:00
/**
* Scan the blockchain looking for addresses having some activity
*
* @param {Object} opts
* @param {Boolean} opts.includeCopayerBranches (defaults to false)
*/
WalletService.prototype.scan = function(opts, cb) {
2015-04-01 12:42:12 -07:00
var self = this;
opts = opts || {};
2015-04-01 13:48:54 -07:00
function deriveAddresses(size, derivator, cb) {
2015-04-01 14:25:18 -07:00
async.mapSeries(_.range(size), function(i, next) {
2015-04-01 13:21:06 -07:00
setTimeout(function() {
2015-04-17 14:25:41 -07:00
next(null, derivator.derive());
2015-08-13 13:24:49 -07:00
}, WalletService.SCAN_CONFIG.derivationDelay)
2015-04-01 12:42:12 -07:00
}, cb);
};
2015-04-15 09:23:30 -07:00
function checkActivity(addresses, networkName, cb) {
2015-07-15 18:42:05 -07:00
var bc = self._getBlockchainExplorer(networkName);
2015-04-01 12:42:12 -07:00
bc.getAddressActivity(addresses, cb);
};
2015-04-01 13:48:54 -07:00
function scanBranch(derivator, cb) {
2015-04-01 12:42:12 -07:00
var activity = true;
var allAddresses = [];
2015-04-15 09:23:30 -07:00
var networkName;
2015-04-01 12:42:12 -07:00
async.whilst(function() {
return activity;
}, function(next) {
2015-08-13 13:24:49 -07:00
deriveAddresses(WalletService.SCAN_CONFIG.scanWindow, derivator, function(err, addresses) {
2015-04-01 12:42:12 -07:00
if (err) return next(err);
2015-04-15 09:23:30 -07:00
networkName = networkName || Bitcore.Address(addresses[0].address).toObject().network;
checkActivity(_.pluck(addresses, 'address'), networkName, function(err, thereIsActivity) {
if (err) return next(err);
2015-05-15 07:25:54 -07:00
2015-04-01 12:42:12 -07:00
activity = thereIsActivity;
2015-04-17 14:25:41 -07:00
if (thereIsActivity) {
allAddresses.push(addresses);
} else {
2015-08-13 13:24:49 -07:00
derivator.rewind(WalletService.SCAN_CONFIG.scanWindow);
2015-04-17 14:25:41 -07:00
}
2015-04-01 12:42:12 -07:00
next();
});
});
}, function(err) {
return cb(err, _.flatten(allAddresses));
});
2015-04-01 12:42:12 -07:00
};
2015-04-08 11:18:28 -07:00
self._runLocked(cb, function(cb) {
2015-04-01 12:42:12 -07:00
self.getWallet({}, function(err, wallet) {
if (err) return cb(err);
2015-08-05 06:44:09 -07:00
if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE);
2015-04-01 12:42:12 -07:00
2015-04-15 06:57:10 -07:00
wallet.scanStatus = 'running';
self.storage.storeWallet(wallet, function(err) {
if (err) return cb(err);
2015-04-01 12:42:12 -07:00
2015-04-15 06:57:10 -07:00
var derivators = [];
_.each([false, true], function(isChange) {
2015-04-17 14:25:41 -07:00
derivators.push({
derive: _.bind(wallet.createAddress, wallet, isChange),
rewind: _.bind(wallet.addressManager.rewindIndex, wallet.addressManager, isChange),
});
2015-04-15 06:57:10 -07:00
if (opts.includeCopayerBranches) {
_.each(wallet.copayers, function(copayer) {
if (copayer.addressManager) {
2015-08-27 13:14:33 -07:00
derivators.push({
derive: _.bind(copayer.createAddress, copayer, wallet, isChange),
rewind: _.bind(copayer.addressManager.rewindIndex, copayer.addressManager, isChange),
});
}
2015-04-15 06:57:10 -07:00
});
}
});
async.eachSeries(derivators, function(derivator, next) {
scanBranch(derivator, function(err, addresses) {
if (err) return next(err);
self.storage.storeAddressAndWallet(wallet, addresses, next);
});
}, function(error) {
self.storage.fetchWallet(wallet.id, function(err, wallet) {
if (err) return cb(err);
wallet.scanStatus = error ? 'error' : 'success';
self.storage.storeWallet(wallet, function() {
return cb(error);
});
})
2015-04-01 12:42:12 -07:00
});
2015-04-15 06:57:10 -07:00
});
2015-04-01 12:42:12 -07:00
});
});
2015-04-02 07:18:39 -07:00
};
/**
* Start a scan process.
*
* @param {Object} opts
* @param {Boolean} opts.includeCopayerBranches (defaults to false)
*/
WalletService.prototype.startScan = function(opts, cb) {
var self = this;
function scanFinished(err) {
2015-04-14 11:41:27 -07:00
var data = {
2015-04-15 06:57:10 -07:00
result: err ? 'error' : 'success',
2015-04-14 11:41:27 -07:00
};
if (err) data.error = err;
2015-05-07 10:16:24 -07:00
self._notify('ScanFinished', data, {
isGlobal: true
});
2015-04-02 07:18:39 -07:00
};
2015-04-03 14:49:08 -07:00
self.getWallet({}, function(err, wallet) {
if (err) return cb(err);
2015-08-05 06:44:09 -07:00
if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE);
2015-04-02 07:18:39 -07:00
2015-04-15 06:57:10 -07:00
setTimeout(function() {
self.scan(opts, scanFinished);
}, 100);
2015-04-15 06:57:10 -07:00
return cb(null, {
started: true
});
2015-04-02 07:18:39 -07:00
});
};
2015-04-02 07:18:39 -07:00
2015-02-20 12:32:19 -08:00
module.exports = WalletService;
2015-02-09 10:30:16 -08:00
module.exports.ClientError = ClientError;