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.

431 lines
12 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;
10 years ago
var Bitcore = require('bitcore');
var Explorers = require('bitcore-explorers');
10 years ago
var Lock = require('./lock');
var Storage = require('./storage');
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
};
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;
10 years ago
// TODO: validate opts.pubKey is valid and belongs to opts.network
10 years ago
self.storage.fetchWallet(opts.id, function (err, wallet) {
10 years ago
if (err) return cb(err);
if (wallet) return cb('Wallet already exists');
var wallet = new Wallet({
id: opts.id,
name: opts.name,
m: opts.m,
n: opts.n,
network: opts.network || 'livenet',
pubKey: opts.pubKey,
});
self.storage.storeWallet(wallet, cb);
});
};
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
*/
CopayServer.prototype.getWallet = function (opts, cb) {
10 years ago
var self = this;
self.storage.fetchWallet(opts.id, function (err, wallet) {
10 years ago
if (err) return cb(err);
if (!wallet) return cb('Wallet not found');
10 years ago
return cb(null, wallet);
10 years ago
});
};
10 years ago
10 years ago
CopayServer.prototype._runLocked = function (walletId, cb, task) {
10 years ago
var self = this;
Lock.get(walletId, function (lock) {
var _cb = function () {
cb.apply(null, arguments);
lock.free();
};
task(_cb);
});
};
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.
*/
CopayServer.prototype.joinWallet = function (opts, cb) {
10 years ago
var self = this;
10 years ago
self._runLocked(opts.walletId, cb, function (cb) {
10 years ago
self.getWallet({ id: opts.walletId }, function (err, wallet) {
10 years ago
if (err) return cb(err);
10 years ago
if (_.find(wallet.copayers, { xPubKey: opts.xPubKey })) return cb('Copayer already in wallet');
if (wallet.copayers.length == wallet.n) return cb('Wallet full');
10 years ago
// TODO: validate copayer's extended public key using the public key from this wallet
// Note: use Bitcore.crypto.ecdsa .verify()
var copayer = new Copayer({
id: opts.id,
name: opts.name,
xPubKey: opts.xPubKey,
xPubKeySignature: opts.xPubKeySignature,
});
10 years ago
wallet.addCopayer(copayer);
self.storage.storeWallet(wallet, function (err) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
return cb();
10 years ago
});
});
});
};
10 years ago
CopayServer.prototype._doCreateAddress = function (pkr, index, isChange) {
10 years ago
throw 'not implemented';
};
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
*/
CopayServer.prototype.createAddress = function (opts, cb) {
10 years ago
var self = this;
10 years ago
self._runLocked(opts.walletId, cb, function (cb) {
self.getWallet({ id: opts.walletId }, function (err, wallet) {
10 years ago
if (err) return cb(err);
10 years ago
var index = wallet.addressIndex++;
self.storage.storeWallet(wallet, function (err) {
10 years ago
if (err) return cb(err);
10 years ago
var address = self._doCreateAddress(wallet.publicKeyRing, index, opts.isChange);
self.storage.storeAddress(opts.walletId, address, function (err) {
if (err) return cb(err);
return cb(null, address);
});
10 years ago
});
});
10 years ago
});
};
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.
*/
CopayServer.prototype.verifyMessageSignature = function (opts, cb) {
var self = this;
10 years ago
self.getWallet({ id: opts.walletId }, function (err, wallet) {
10 years ago
if (err) return cb(err);
10 years ago
var copayer = wallet.getCopayer(opts.copayerId);
10 years ago
if (!copayer) return cb('Copayer not found');
var isValid = self._doVerifyMessageSignature(copayer.xPubKey, opts.message, opts.signature);
return cb(null, isValid);
});
};
CopayServer.prototype._doVerifyMessageSignature = function (pubKey, message, signature) {
10 years ago
throw 'not implemented';
};
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;
}
10 years ago
return new Explorers.Insight(url, network);
10 years ago
break;
}
};
CopayServer.prototype._getUtxos = function (opts, cb) {
var self = this;
// Get addresses for this wallet
10 years ago
self.storage.fetchAddresses(opts.walletId, function (err, addresses) {
10 years ago
if (err) return cb(err);
if (addresses.length == 0) return cb('The wallet has no addresses');
var addresses = _.pluck(addresses, 'address');
10 years ago
var bc = self._getBlockExplorer('insight', opts.network);
10 years ago
bc.getUnspentUtxos(addresses, 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)
10 years ago
.pluck('inputs')
10 years ago
.flatten()
.map(function (utxo) { return utxo.txid + '|' + utxo.vout });
10 years ago
10 years ago
var dictionary = _.groupBy(utxos, function (utxo) {
return utxo.txid + '|' + utxo.vout;
});
_.each(inputs, function (input) {
if (dictionary[input]) {
dictionary[input].locked = true;
}
});
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.
*/
CopayServer.prototype.getBalance = function (opts, cb) {
var self = this;
self._getUtxos({ walletId: opts.walletId }, function (err, utxos) {
if (err) return cb(err);
var balance = {};
10 years ago
balance.totalAmount = _.reduce(utxos, function(sum, utxo) { return sum + utxo.amount; }, 0);
balance.lockedAmount = _.reduce(_.without(utxos, { locked: true }), function(sum, utxo) { return sum + utxo.amount; }, 0);
10 years ago
return cb(null, balance);
});
};
10 years ago
CopayServer.prototype._createRawTx = function (txp) {
10 years ago
var rawTx = new Bitcore.Transaction()
10 years ago
.from(tx.inputs)
10 years ago
.to(txp.toAddress, txp.amount)
.change(txp.changeAddress);
10 years ago
10 years ago
return rawTx;
10 years ago
};
10 years ago
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]);
total += inputs[i].amount;
if (total >= txp.amount) {
break;
}
i++;
};
return selected;
};
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.
10 years ago
* @returns {TxProposal} Transaction proposal.
10 years ago
*/
10 years ago
CopayServer.prototype.createTx = function (opts, cb) {
var self = this;
self.getWallet({ id: opts.walletId }, function (err, wallet) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
self._getUtxos({ walletId: wallet.id }, function (err, utxos) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
utxos = _.without(utxos, { locked: true });
10 years ago
var txp = new TxProposal({
creatorId: opts.copayerId,
toAddress: opts.toAddress,
amount: opts.amount,
10 years ago
inputs: self._selectUtxos(opts.amount, utxos),
10 years ago
changeAddress: opts.changeAddress,
requiredSignatures: wallet.m,
maxRejections: wallet.n - wallet.m,
});
10 years ago
10 years ago
txp.rawTx = self._createRawTx(txp);
10 years ago
10 years ago
self.storage.storeTx(wallet.id, txp, function (err) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
return cb(null, txp);
10 years ago
});
});
});
};
10 years ago
CopayServer.prototype._broadcastTx = function (rawTx, cb) {
10 years ago
// TODO: this should attempt to broadcast _all_ accepted and not-yet broadcasted (status=='accepted') txps?
10 years ago
cb = cb || function () {};
throw 'not implemented';
};
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.signature - The signature of the tx for this copayer.
*/
CopayServer.prototype.signTx = function (opts, cb) {
var self = this;
10 years ago
self.fetchTx(opts.walletId, opts.txProposalId, function (err, txp) {
10 years ago
if (err) return cb(err);
10 years ago
if (!txp) return cb('Transaction proposal not found');
var action = _.find(txp.actions, { copayerId: opts.copayerId });
if (action) return cb('Copayer already voted on this transaction proposal');
if (txp.status != 'pending') return cb('The transaction proposal is not pending');
10 years ago
10 years ago
txp.sign(opts.copayerId, opts.signature);
10 years ago
10 years ago
self.storage.storeTx(opts.walletId, txp, function (err) {
if (err) return cb(err);
10 years ago
10 years ago
if (txp.status == 'accepted');
self._broadcastTx(txp.rawTx, function (err, txid) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
tx.setBroadcasted(txid);
self.storage.storeTx(opts.walletId, txp, function (err) {
10 years ago
if (err) return cb(err);
10 years ago
10 years ago
return cb();
10 years ago
});
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.
*/
CopayServer.prototype.rejectTx = function (opts, cb) {
var self = this;
self.fetchTx(opts.walletId, opts.txProposalId, function (err, txp) {
if (err) return cb(err);
if (!txp) return cb('Transaction proposal not found');
var action = _.find(txp.actions, { copayerId: opts.copayerId });
if (action) return cb('Copayer already voted on this transaction proposal');
if (txp.status != 'pending') return cb('The transaction proposal is not pending');
txp.reject(opts.copayerId);
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
CopayServer.prototype.getPendingTxs = function (opts, cb) {
var self = this;
10 years ago
self.storage.fetchTxs(opts.walletId, function (err, txps) {
10 years ago
if (err) return cb(err);
10 years ago
var pending = _.filter(txps, { status: 'pending' });
10 years ago
10 years ago
return cb(null, pending);
10 years ago
});
10 years ago
};
module.exports = CopayServer;