diff --git a/lib/transaction/transaction.js b/lib/transaction/transaction.js index 6bf1c27..d5fdcff 100644 --- a/lib/transaction/transaction.js +++ b/lib/transaction/transaction.js @@ -914,16 +914,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 8a783a8..b828ec5 100644 --- a/test/transaction/transaction.js +++ b/test/transaction/transaction.js @@ -830,15 +830,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() {