From d4865de91dd80c59b5e5cf8f77a1ebf6bd87682b Mon Sep 17 00:00:00 2001 From: Ivan Socolsky Date: Mon, 2 Feb 2015 22:00:11 -0300 Subject: [PATCH] fix UTXOs selection & balance calculation --- lib/server.js | 15 +++++++++------ test/integration.js | 4 ++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/server.js b/lib/server.js index 54c417d..bd154ab 100644 --- a/lib/server.js +++ b/lib/server.js @@ -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); diff --git a/test/integration.js b/test/integration.js index c929ee9..06a3a4e 100644 --- a/test/integration.js +++ b/test/integration.js @@ -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(); }); });