From a057dc4064817dd12f6264ef6fb94062d24757b0 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 23 Dec 2015 02:42:36 -0800 Subject: [PATCH] use big numbers when calculating fee. --- lib/bcoin/tx.js | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 025fbe5c..f854ad1b 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -649,7 +649,7 @@ TX.prototype.maxSize = function maxSize() { } }, this); - return size; + return new bn(size); }; TX.prototype.utxos = function utxos(unspent) { @@ -657,10 +657,10 @@ TX.prototype.utxos = function utxos(unspent) { var cost = this.funds('out'); // Use initial fee for starters - var fee = 1; + var fee = new bn(1); // total = cost + fee - var total = cost.add(new bn(TX.fee)); + var total = cost.addn(TX.fee); var inputs = this.inputs.slice(); var utxos = []; @@ -691,9 +691,11 @@ TX.prototype.utxos = function utxos(unspent) { // Calculate maximum possible size after signing byteSize = this.maxSize(); - addFee = Math.ceil(byteSize / 1024) - fee; - total.iadd(new bn(addFee * TX.fee)); - fee += addFee; + addFee = byteSize.modn(1024) === 0 + ? byteSize.divn(1024).sub(fee) + : byteSize.divn(1024).addn(1).sub(fee); + total.iadd(addFee.muln(TX.fee)); + fee.iadd(addFee); // Failed to get enough funds, add more inputs if (this.funds('in').cmp(total) < 0) @@ -765,24 +767,26 @@ TX.prototype._recalculateFee = function recalculateFee() { } var byteSize = this.maxSize(); - var newFee = Math.ceil(byteSize / 1024) * TX.fee; - var currentFee = this.getFee().toNumber(); + var newFee = byteSize.modn(1024) === 0 + ? 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) this.outputs.pop(); return; } - if (newFee > currentFee) { - if (output.value.cmpn(newFee - currentFee) < 0) { + if (newFee.cmp(currentFee) > 0) { + if (output.value.cmp(newFee.sub(currentFee)) < 0) { this.outputs.pop(); this.changeOutput = null; return; } - output.value.isubn(newFee - currentFee); + output.value.isub(newFee.sub(currentFee)); } else { - output.value.iaddn(currentFee - newFee); + output.value.iadd(currentFee.sub(newFee)); } if (output.value.cmpn(TX.dust) < 0) {