diff --git a/lib/transaction/transaction.js b/lib/transaction/transaction.js index 158627c..02b6276 100644 --- a/lib/transaction/transaction.js +++ b/lib/transaction/transaction.js @@ -421,11 +421,11 @@ Transaction.prototype.addInput = function(input, outputScript, satoshis) { */ Transaction.prototype.uncheckedAddInput = function(input) { $.checkArgumentType(input, Input, 'input'); - this._changeSetup = false; this.inputs.push(input); if (input.output) { this._inputAmount += input.output.satoshis; } + this._updateChangeOutput(); return this; }; @@ -450,7 +450,7 @@ Transaction.prototype.hasAllUtxoInfo = function() { */ Transaction.prototype.fee = function(amount) { this._fee = amount; - this._changeSetup = false; + this._updateChangeOutput(); return this; }; @@ -467,7 +467,7 @@ Transaction.prototype.fee = function(amount) { */ Transaction.prototype.change = function(address) { this._change = new Address(address); - this._changeSetup = false; + this._updateChangeOutput(); return this; }; @@ -509,8 +509,12 @@ Transaction.prototype.addData = function(value) { Transaction.prototype.addOutput = function(output) { $.checkArgumentType(output, Output, 'output'); + this._addOutput(output); + this._updateChangeOutput(); +}; + +Transaction.prototype._addOutput = function(output) { this.outputs.push(output); - this._changeSetup = false; this._outputAmount += output.satoshis; }; @@ -518,12 +522,7 @@ Transaction.prototype._updateChangeOutput = function() { if (!this._change) { return; } - if (this._changeSetup) { - return; - } - if (!_.isUndefined(this._changeSetup)) { - this._clearSignatures(); - } + this._clearSignatures(); if (!_.isUndefined(this._changeOutput)) { this.removeOutput(this._changeOutput); } @@ -531,14 +530,13 @@ Transaction.prototype._updateChangeOutput = function() { var fee = this.getFee(); if (available - fee > 0) { this._changeOutput = this.outputs.length; - this.addOutput(new Output({ + this._addOutput(new Output({ script: Script.fromAddress(this._change), satoshis: available - fee })); } else { this._changeOutput = undefined; } - this._changeSetup = true; }; Transaction.prototype.getFee = function() { @@ -606,7 +604,6 @@ Transaction.prototype.removeOutput = function(index) { */ Transaction.prototype.sign = function(privateKey, sigtype) { $.checkState(this.hasAllUtxoInfo()); - this._updateChangeOutput(); var self = this; if (_.isArray(privateKey)) { _.each(privateKey, function(privateKey) { diff --git a/test/transaction/transaction.js b/test/transaction/transaction.js index cb8938c..3460712 100644 --- a/test/transaction/transaction.js +++ b/test/transaction/transaction.js @@ -260,7 +260,8 @@ describe('Transaction', function() { var transaction = new Transaction() .from(simpleUtxoWith1BTC) .change(changeAddress) - .to(toAddress, 1); + .fee(50000000) + .to(toAddress, 40000000); expect(function() { return transaction.serialize(); }).to.throw(errors.Transaction.FeeError);