fix UTXOs selection & balance calculation

This commit is contained in:
Ivan Socolsky 2015-02-02 22:00:11 -03:00
parent 1d8360b79a
commit d4865de91d
2 changed files with 11 additions and 8 deletions

View File

@ -270,11 +270,13 @@ CopayServer.prototype._getUtxos = function(opts, cb) {
.flatten()
.map(function(utxo) {
return utxo.txid + '|' + utxo.vout
});
})
.value();
var dictionary = _.groupBy(utxos, function(utxo) {
return utxo.txid + '|' + utxo.vout;
});
var dictionary = _.reduce(utxos, function (memo, utxo) {
memo[utxo.txid + '|' + utxo.vout] = utxo;
return memo;
}, {});
_.each(inputs, function(input) {
if (dictionary[input]) {
@ -308,7 +310,7 @@ CopayServer.prototype.getBalance = function(opts, cb) {
balance.totalAmount = _.reduce(utxos, function(sum, utxo) {
return sum + utxo.amount;
}, 0);
balance.lockedAmount = _.reduce(_.without(utxos, {
balance.lockedAmount = _.reduce(_.filter(utxos, {
locked: true
}), function(sum, utxo) {
return sum + utxo.amount;
@ -333,6 +335,7 @@ CopayServer.prototype._selectUtxos = function(txp, utxos) {
var total = 0;
var selected = [];
var inputs = _.sortBy(utxos, 'amount');
while (i < inputs.length) {
selected.push(inputs[i]);
total += inputs[i].amount;
@ -378,11 +381,11 @@ CopayServer.prototype.createTx = function(opts, cb) {
creatorId: opts.copayerId,
toAddress: opts.toAddress,
amount: opts.amount,
inputs: self._selectUtxos(opts.amount, utxos),
changeAddress: opts.changeAddress,
requiredSignatures: wallet.m,
maxRejections: wallet.n - wallet.m,
});
txp.inputs = self._selectUtxos(txp, utxos);
txp.rawTx = self._createRawTx(txp);

View File

@ -594,7 +594,7 @@ describe('Copay server', function() {
});
});
it.only('should create tx', function(done) {
it('should create tx', function(done) {
var bc = sinon.stub();
bc.getUnspentUtxos = sinon.stub().callsArgWith(1, null, helpers.createUtxos([100, 200]));
server._getBlockExplorer = sinon.stub().returns(bc);
@ -626,7 +626,7 @@ describe('Copay server', function() {
}, function(err, balance) {
should.not.exist(err);
balance.totalAmount.should.equal(300);
balance.lockedAmount.should.equal(200);
balance.lockedAmount.should.equal(100);
done();
});
});