You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

592 lines
16 KiB

10 years ago
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var async = require('async');
var log = require('npmlog');
log.debug = log.verbose;
var inherits = require('inherits');
var events = require('events');
10 years ago
var Bitcore = require('bitcore');
var PublicKey = Bitcore.PublicKey;
var HDPublicKey = Bitcore.HDPublicKey;
10 years ago
var Explorers = require('bitcore-explorers');
10 years ago
var ClientError = require('./clienterror');
var Utils = require('./utils');
10 years ago
var Storage = require('./storage');
10 years ago
var SignUtils = require('./signutils');
10 years ago
10 years ago
var Wallet = require('./model/wallet');
var Copayer = require('./model/copayer');
10 years ago
var Address = require('./model/address');
var TxProposal = require('./model/txproposal');
10 years ago
10 years ago
/**
* Creates an instance of the Copay server.
* @constructor
10 years ago
* @param {Object} opts
* @param {Storage} [opts.storage] - The storage provider.
10 years ago
*/
10 years ago
function CopayServer(opts) {
opts = opts || {};
10 years ago
this.storage = opts.storage ||  new Storage();
10 years ago
};
inherits(CopayServer, events.EventEmitter);
10 years ago
CopayServer._emit = function(event) {
var args = Array.prototype.slice.call(arguments);
log.debug('Emitting: ', args);
this.emit.apply(this, arguments);
};
10 years ago
10 years ago
/**
* Creates a new wallet.
10 years ago
* @param {Object} opts
10 years ago
* @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.
*/
10 years ago
CopayServer.prototype.createWallet = function(opts, cb) {
var self = this,
pubKey;
10 years ago
Utils.checkRequired(opts, ['id', 'name', 'm', 'n', 'pubKey']);
if (!Wallet.verifyCopayerLimits(opts.m, opts.n)) return cb(new ClientError('Invalid combination of required copayers / total copayers'));
var network = opts.network || 'livenet';
if (network != 'livenet' && network != 'testnet') return cb(new ClientError('Invalid network'));
try {
pubKey = new PublicKey.fromString(opts.pubKey);
} catch (e) {
return cb(e.toString());
};
10 years ago
10 years ago
self.storage.fetchWallet(opts.id, function(err, wallet) {
if (err) return cb(err);
if (wallet) return cb(new ClientError('WEXISTS', 'Wallet already exists'));
var wallet = new Wallet({
id: opts.id,
name: opts.name,
m: opts.m,
n: opts.n,
network: opts.network || 'livenet',
pubKey: pubKey,
});
self.storage.storeWallet(wallet, cb);
});
10 years ago
};
10 years ago
/**
* Retrieves a wallet from storage.
10 years ago
* @param {Object} opts
10 years ago
* @param {string} opts.id - The wallet id.
* @returns {Object} wallet
10 years ago
*/
10 years ago
CopayServer.prototype.getWallet = function(opts, cb) {
var self = this;
10 years ago
10 years ago
self.storage.fetchWallet(opts.id, function(err, wallet) {
if (err) return cb(err);
if (!wallet) return cb(new ClientError('Wallet not found'));
return cb(null, wallet);
});
10 years ago
};
10 years ago
10 years ago
/**
* Verifies a signature
* @param text
* @param signature
* @param pubKey
*/
CopayServer.prototype._verifySignature = function(text, signature, pubKey) {
return SignUtils.verify(text, signature, pubKey);
10 years ago
};
10 years ago
/**
* Joins a wallet in creation.
10 years ago
* @param {Object} opts
10 years ago
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.id - The copayer 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.
*/
10 years ago
CopayServer.prototype.joinWallet = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, ['walletId', 'id', 'name', 'xPubKey', 'xPubKeySignature']);
10 years ago
Utils.runLocked(opts.walletId, cb, function(cb) {
self.getWallet({
id: opts.walletId
}, function(err, wallet) {
if (err) return cb(err);
10 years ago
if (!self._verifySignature(opts.xPubKey, opts.xPubKeySignature, wallet.pubKey)) {
return cb(new ClientError());
10 years ago
}
if (_.find(wallet.copayers, {
xPubKey: opts.xPubKey
})) return cb(new ClientError('CINWALLET', 'Copayer already in wallet'));
if (wallet.copayers.length == wallet.n) return cb(new ClientError('WFULL', 'Wallet full'));
var copayer = new Copayer({
id: opts.id,
name: opts.name,
xPubKey: opts.xPubKey,
xPubKeySignature: opts.xPubKeySignature,
copayerIndex: wallet.copayers.length,
});
10 years ago
wallet.addCopayer(copayer);
10 years ago
self.storage.storeWallet(wallet, function(err) {
return cb(err);
});
});
});
10 years ago
};
10 years ago
/**
10 years ago
*
* TODO: How this is going to be authenticated?
*
10 years ago
* Creates a new address.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @param {truthy} opts.isChange - Indicates whether this is a regular address or a change address.
* @returns {Address} address
10 years ago
*/
10 years ago
CopayServer.prototype.createAddress = function(opts, cb) {
var self = this;
var isChange = opts.isChange || false;
Utils.checkRequired(opts, ['walletId', 'isChange']);
10 years ago
Utils.runLocked(opts.walletId, cb, function(cb) {
self.getWallet({
id: opts.walletId
}, function(err, wallet) {
if (err) return cb(err);
10 years ago
var address = wallet.createAddress(opts.isChange);
self.storage.storeAddress(wallet.id, address, function(err) {
if (err) return cb(err);
10 years ago
self.storage.storeWallet(wallet, function(err) {
if (err) {
10 years ago
self.storage.removeAddress(wallet.id, address, function() {
return cb(err);
});
} else {
return cb(null, address);
}
});
});
});
});
10 years ago
};
/**
* Get all addresses.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @returns {Address[]}
*/
10 years ago
CopayServer.prototype.getAddresses = function(opts, cb) {
var self = this;
self.storage.fetchAddresses(opts.walletId, function(err, addresses) {
if (err) return cb(err);
return cb(null, addresses);
});
};
10 years ago
/**
* Verifies that a given message was actually sent by an authorized copayer.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.copayerId - The wallet id.
* @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.
*/
10 years ago
CopayServer.prototype.verifyMessageSignature = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, ['walletId', 'copayerId', 'message', 'signature']);
10 years ago
self.getWallet({
id: opts.walletId
}, function(err, wallet) {
if (err) return cb(err);
10 years ago
var copayer = wallet.getCopayer(opts.copayerId);
if (!copayer) return cb(new ClientError('Copayer not found'));
10 years ago
var isValid = self._verifySignature(opts.message, opts.signature, copayer.signingPubKey);
return cb(null, isValid);
});
10 years ago
};
10 years ago
10 years ago
CopayServer.prototype._getBlockExplorer = function(provider, network) {
var url;
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;
}
return new Explorers.Insight(url, network);
break;
}
10 years ago
};
10 years ago
/**
* _getUtxos
*
* @param opts.walletId
*/
10 years ago
CopayServer.prototype._getUtxos = function(opts, cb) {
var self = this;
10 years ago
self.storage.fetchWallet(opts.walletId, function(err, wallet) {
if (err) return cb(err);
10 years ago
// Get addresses for this wallet
self.storage.fetchAddresses(opts.walletId, function(err, addresses) {
if (err) return cb(err);
10 years ago
if (addresses.length == 0) return cb(new ClientError('The wallet has no addresses'));
var addressStrs = _.pluck(addresses, 'address');
var addressToPath = _.indexBy(addresses, 'address'); // TODO : check performance
10 years ago
var bc = self._getBlockExplorer('insight', wallet.getNetworkName());
bc.getUnspentUtxos(addressStrs, function(err, utxos) {
if (err) return cb(err);
10 years ago
self.getPendingTxs({
walletId: opts.walletId
}, function(err, txps) {
if (err) return cb(err);
var inputs = _.chain(txps)
.pluck('inputs')
.flatten()
.map(function(utxo) {
return utxo.txid + '|' + utxo.vout
})
.value();
var dictionary = _.reduce(utxos, function(memo, utxo) {
memo[utxo.txid + '|' + utxo.vout] = utxo;
return memo;
}, {});
_.each(inputs, function(input) {
if (dictionary[input]) {
dictionary[input].locked = true;
}
});
10 years ago
10 years ago
// Needed for the clients to sign UTXOs
_.each(utxos, function(utxo) {
utxo.path = addressToPath[utxo.address].path;
utxo.publicKeys = addressToPath[utxo.address].publicKeys;
});
10 years ago
10 years ago
return cb(null, utxos);
});
});
});
});
10 years ago
};
10 years ago
/**
* Creates a new transaction proposal.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @returns {Object} balance - Total amount & locked amount.
10 years ago
*/
10 years ago
CopayServer.prototype.getBalance = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, 'walletId');
10 years ago
self._getUtxos({
walletId: opts.walletId
}, function(err, utxos) {
if (err) return cb(err);
10 years ago
var balance = {};
10 years ago
balance.totalAmount = Utils.strip(_.reduce(utxos, function(sum, utxo) {
10 years ago
return sum + self._inputSatoshis(utxo);
10 years ago
}, 0));
balance.lockedAmount = Utils.strip(_.reduce(_.filter(utxos, {
10 years ago
locked: true
}), function(sum, utxo) {
10 years ago
return sum + self._inputSatoshis(utxo);
10 years ago
}, 0));
10 years ago
return cb(null, balance);
});
10 years ago
};
10 years ago
CopayServer.prototype._inputSatoshis = function(i) {
return i.amount ? Utils.strip(i.amount * 1e8) : i.satoshis;
};
CopayServer.prototype._selectUtxos = function(txp, utxos) {
var i = 0;
var total = 0;
var selected = [];
var inputs = _.sortBy(utxos, 'amount');
while (i < inputs.length) {
selected.push(inputs[i]);
10 years ago
total += this._inputSatoshis(inputs[i]);
if (total >= txp.amount) {
10 years ago
break;
}
i++;
};
10 years ago
return total >= txp.amount ? selected : null;
10 years ago
};
10 years ago
10 years ago
/**
* Creates a new transaction proposal.
10 years ago
* @param {Object} opts
10 years ago
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.copayerId - The wallet id.
* @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.
* @returns {TxProposal} Transaction proposal.
10 years ago
*/
10 years ago
CopayServer.prototype.createTx = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, ['walletId', 'copayerId', 'toAddress', 'amount', 'message']);
10 years ago
// TODO?
// Check some parameters like:
// amount > dust
10 years ago
self.getWallet({
id: opts.walletId
}, function(err, wallet) {
if (err) return cb(err);
10 years ago
10 years ago
self._getUtxos({
walletId: wallet.id
}, function(err, utxos) {
if (err) return cb(err);
10 years ago
10 years ago
var changeAddress = wallet.createAddress(true).address;
utxos = _.reject(utxos, {
10 years ago
locked: true
});
10 years ago
var txp = new TxProposal({
creatorId: opts.copayerId,
toAddress: opts.toAddress,
amount: opts.amount,
10 years ago
changeAddress: changeAddress,
requiredSignatures: wallet.m,
maxRejections: wallet.n - wallet.m,
});
10 years ago
10 years ago
txp.inputs = self._selectUtxos(txp, utxos);
if (!txp.inputs) {
return cb(new ClientError('INSUFFICIENTFUNDS', 'Insufficient funds'));
}
10 years ago
10 years ago
txp.inputPaths = _.pluck(txp.inputs, 'path');
10 years ago
10 years ago
// no need to do this now: // TODO remove this comment
//self._createRawTx(txp);
10 years ago
self.storage.storeTx(wallet.id, txp, function(err) {
if (err) return cb(err);
10 years ago
return cb(null, txp);
});
});
});
10 years ago
};
10 years ago
10 years ago
/**
* Retrieves a tx from storage.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.id - The tx id.
* @returns {Object} txProposal
*/
CopayServer.prototype.getTx = function(opts, cb) {
var self = this;
self.storage.fetchTx(opts.walletId, opts.id, function(err, txp) {
if (err) return cb(err);
if (!txp) return cb(new ClientError('Transaction proposal not found'));
return cb(null, txp);
});
};
10 years ago
CopayServer.prototype._broadcastTx = function(txp, networkName, cb) {
var raw = txp.getRawTx();
var bc = self._getBlockExplorer('insight', networkName);
bc.broadcast(raw, function(err, txid) {
return cb(err, txid);
})
10 years ago
};
10 years ago
/**
* Sign a transaction proposal.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.copayerId - The wallet id.
10 years ago
* @param {string} opts.txProposalId - The identifier of the transaction.
10 years ago
* @param {string} opts.signatures - The signatures of the inputs of this tx for this copayer (in apperance order)
10 years ago
*/
10 years ago
CopayServer.prototype.signTx = function(opts, cb) {
var self = this;
10 years ago
10 years ago
Utils.checkRequired(opts, ['walletId', 'copayerId', 'txProposalId', 'signatures']);
self.getWallet({
id: opts.walletId
}, function(err, wallet) {
if (err) return cb(err);
10 years ago
self.getTx({
walletId: opts.walletId,
id: opts.txProposalId
}, function(err, txp) {
if (err) return cb(err);
if (!txp) return cb(new ClientError('Transaction proposal not found'));
var action = _.find(txp.actions, {
copayerId: opts.copayerId
});
10 years ago
if (action)
return cb(new ClientError('CVOTED', 'Copayer already voted on this transaction proposal'));
10 years ago
if (txp.status != 'pending')
return cb(new ClientError('TXNOTPENDING', 'The transaction proposal is not pending'));
10 years ago
var copayer = wallet.getCopayer(opts.copayerId);
10 years ago
if (!txp.checkSignatures(opts.signatures, copayer.xPubKey))
return cb(new ClientError('BADSIGNATURES', 'Bad signatures'));
txp.sign(opts.copayerId, opts.signatures);
self.storage.storeTx(opts.walletId, txp, function(err) {
if (err) return cb(err);
if (txp.status == 'accepted') {
10 years ago
self._broadcastTx(txp, wallet.getNetworkName(), function(err, txid) {
10 years ago
if (err) return cb(err);
tx.setBroadcasted(txid);
self.storage.storeTx(opts.walletId, txp, function(err) {
if (err) return cb(err);
return cb(null, txp);
});
10 years ago
});
} else {
return cb(null, txp);
}
});
});
});
};
10 years ago
10 years ago
/**
* Reject a transaction proposal.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @param {string} opts.copayerId - The wallet id.
* @param {string} opts.txProposalId - The identifier of the transaction.
* @param {string} [opts.reason] - A message to other copayers explaining the rejection.
10 years ago
*/
10 years ago
CopayServer.prototype.rejectTx = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, ['walletId', 'copayerId', 'txProposalId']);
self.getTx({
walletId: opts.walletId,
id: opts.txProposalId
}, function(err, txp) {
if (err) return cb(err);
if (!txp) return cb(new ClientError('Transaction proposal not found'));
10 years ago
var action = _.find(txp.actions, {
copayerId: opts.copayerId
});
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'));
10 years ago
txp.reject(opts.copayerId);
10 years ago
10 years ago
self.storage.storeTx(opts.walletId, txp, function(err) {
if (err) return cb(err);
10 years ago
return cb();
});
});
10 years ago
};
10 years ago
/**
* Retrieves all pending transaction proposals.
* @param {Object} opts
* @param {string} opts.walletId - The wallet id.
* @returns {TxProposal[]} Transaction proposal.
10 years ago
*/
10 years ago
CopayServer.prototype.getPendingTxs = function(opts, cb) {
var self = this;
10 years ago
Utils.checkRequired(opts, 'walletId');
10 years ago
self.storage.fetchTxs(opts.walletId, function(err, txps) {
if (err) return cb(err);
10 years ago
10 years ago
var pending = _.filter(txps, {
status: 'pending'
});
return cb(null, pending);
});
10 years ago
};
module.exports = CopayServer;