From b9d52b79c8cd3c2172a65cbea1525fe7f8c8fba9 Mon Sep 17 00:00:00 2001 From: Kirill Fomichev Date: Fri, 5 Jun 2015 20:53:36 +0300 Subject: [PATCH] fix Transaction.sortOutputs --- lib/transaction/transaction.js | 16 +++++++++------- test/transaction/transaction.js | 11 ++++++++--- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/lib/transaction/transaction.js b/lib/transaction/transaction.js index 232dafe..fa8b1f8 100644 --- a/lib/transaction/transaction.js +++ b/lib/transaction/transaction.js @@ -899,16 +899,18 @@ Transaction.prototype.sortOutputs = function(sortingFunction) { }; Transaction.prototype._newOutputOrder = function(newOutputs) { - var changeIndex = 0; - var length = this.outputs.length; - while (changeIndex < length && this.outputs[this._changeIndex] !== newOutputs[changeIndex]) { - changeIndex++; - } - if (changeIndex === length) { + var isInvalidSorting = (this.outputs.length !== newOutputs.length || + _.difference(this.outputs, newOutputs).length !== 0); + if (isInvalidSorting) { throw new errors.Transaction.InvalidSorting(); } + + if (!_.isUndefined(this._changeIndex)) { + var changeOutput = this.outputs[this._changeIndex]; + this._changeIndex = _.findIndex(newOutputs, changeOutput); + } + this.outputs = newOutputs; - this._changeIndex = changeIndex; return this; }; diff --git a/test/transaction/transaction.js b/test/transaction/transaction.js index 77ae014..17b62e1 100644 --- a/test/transaction/transaction.js +++ b/test/transaction/transaction.js @@ -812,15 +812,20 @@ describe('Transaction', function() { it('fails if the provided function does not work as expected', function() { var sorting = function(array) { - return []; + return [array[0], array[1], array[2]]; }; expect(function() { transaction.sortOutputs(sorting); }).to.throw(errors.Transaction.InvalidSorting); }); - - + it('shuffle without change', function() { + var tx = new Transaction(transaction.toObject()).to(toAddress, half); + expect(tx.getChangeOutput()).to.be.null; + expect(function() { + tx.shuffleOutputs(); + }).to.not.throw(errors.Transaction.InvalidSorting); + }) }); describe('clearOutputs', function() {