diff --git a/lib/errors/spec.js b/lib/errors/spec.js index 4ce9390..3270c3f 100644 --- a/lib/errors/spec.js +++ b/lib/errors/spec.js @@ -63,6 +63,9 @@ module.exports = [{ }, { name: 'NeedMoreInfo', message: '{0}' + }, { + name: 'InvalidSorting', + message: 'The sorting function provided did not return the change output as one of the array elements' }, { name: 'InvalidOutputAmountSum', message: '{0}' diff --git a/lib/transaction/transaction.js b/lib/transaction/transaction.js index cbf054d..618cc5c 100644 --- a/lib/transaction/transaction.js +++ b/lib/transaction/transaction.js @@ -831,9 +831,13 @@ Transaction.prototype.sortOutputs = function(sortingFunction) { Transaction.prototype._newOutputOrder = function(newOutputs) { var changeIndex = 0; - while (this.outputs[this._changeIndex] !== newOutputs[changeIndex]) { + var length = this.outputs.length; + while (changeIndex < length && this.outputs[this._changeIndex] !== newOutputs[changeIndex]) { changeIndex++; } + if (changeIndex === length) { + throw new errors.Transaction.InvalidSorting(); + } this.outputs = newOutputs; this._changeIndex = changeIndex; return this; diff --git a/test/transaction/transaction.js b/test/transaction/transaction.js index be4a330..26842c4 100644 --- a/test/transaction/transaction.js +++ b/test/transaction/transaction.js @@ -665,6 +665,16 @@ describe('Transaction', function() { _.shuffle.restore(); }); + + it('fails if the provided function does not work as expected', function() { + var sorting = function(array) { + return []; + }; + expect(function() { + transaction.sortOutputs(sorting); + }).to.throw(errors.Transaction.InvalidSorting); + }); + }); });