use big numbers when calculating fee.

This commit is contained in:
Christopher Jeffrey 2015-12-23 02:42:36 -08:00
parent 916d71481b
commit a057dc4064

View File

@ -649,7 +649,7 @@ TX.prototype.maxSize = function maxSize() {
} }
}, this); }, this);
return size; return new bn(size);
}; };
TX.prototype.utxos = function utxos(unspent) { TX.prototype.utxos = function utxos(unspent) {
@ -657,10 +657,10 @@ TX.prototype.utxos = function utxos(unspent) {
var cost = this.funds('out'); var cost = this.funds('out');
// Use initial fee for starters // Use initial fee for starters
var fee = 1; var fee = new bn(1);
// total = cost + fee // total = cost + fee
var total = cost.add(new bn(TX.fee)); var total = cost.addn(TX.fee);
var inputs = this.inputs.slice(); var inputs = this.inputs.slice();
var utxos = []; var utxos = [];
@ -691,9 +691,11 @@ TX.prototype.utxos = function utxos(unspent) {
// Calculate maximum possible size after signing // Calculate maximum possible size after signing
byteSize = this.maxSize(); byteSize = this.maxSize();
addFee = Math.ceil(byteSize / 1024) - fee; addFee = byteSize.modn(1024) === 0
total.iadd(new bn(addFee * TX.fee)); ? byteSize.divn(1024).sub(fee)
fee += addFee; : byteSize.divn(1024).addn(1).sub(fee);
total.iadd(addFee.muln(TX.fee));
fee.iadd(addFee);
// Failed to get enough funds, add more inputs // Failed to get enough funds, add more inputs
if (this.funds('in').cmp(total) < 0) if (this.funds('in').cmp(total) < 0)
@ -765,24 +767,26 @@ TX.prototype._recalculateFee = function recalculateFee() {
} }
var byteSize = this.maxSize(); var byteSize = this.maxSize();
var newFee = Math.ceil(byteSize / 1024) * TX.fee; var newFee = byteSize.modn(1024) === 0
var currentFee = this.getFee().toNumber(); ? byteSize.divn(1024).muln(TX.fee)
: byteSize.divn(1024).addn(1).muln(TX.fee);
var currentFee = this.getFee();
if (newFee === currentFee) { if (newFee.cmp(currentFee) === 0) {
if (!this.changeOutput) if (!this.changeOutput)
this.outputs.pop(); this.outputs.pop();
return; return;
} }
if (newFee > currentFee) { if (newFee.cmp(currentFee) > 0) {
if (output.value.cmpn(newFee - currentFee) < 0) { if (output.value.cmp(newFee.sub(currentFee)) < 0) {
this.outputs.pop(); this.outputs.pop();
this.changeOutput = null; this.changeOutput = null;
return; return;
} }
output.value.isubn(newFee - currentFee); output.value.isub(newFee.sub(currentFee));
} else { } else {
output.value.iaddn(currentFee - newFee); output.value.iadd(currentFee.sub(newFee));
} }
if (output.value.cmpn(TX.dust) < 0) { if (output.value.cmpn(TX.dust) < 0) {