forked from bitcoinjs/coinselect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accumulative.js
38 lines (29 loc) · 1013 Bytes
/
accumulative.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var utils = require('./utils')
// add inputs until we reach or surpass the target value (or deplete)
// worst-case: O(n)
module.exports = function accumulative (utxos, outputs, feeRate) {
if (!isFinite(utils.uintOrNaN(feeRate))) return {}
var bytesAccum = utils.transactionBytes([], outputs)
var inAccum = 0
var inputs = []
var outAccum = utils.sumOrNaN(outputs)
for (var i = 0; i < utxos.length; ++i) {
var utxo = utxos[i]
var utxoBytes = utils.inputBytes(utxo)
var utxoFee = feeRate * utxoBytes
var utxoValue = utils.uintOrNaN(utxo.value)
// skip detrimental input
if (utxoFee > utxo.value) {
if (i === utxos.length - 1) return { fee: feeRate * (bytesAccum + utxoBytes) }
continue
}
bytesAccum += utxoBytes
inAccum += utxoValue
inputs.push(utxo)
var fee = feeRate * bytesAccum
// go again?
if (inAccum < outAccum + fee) continue
return utils.finalize(inputs, outputs, feeRate)
}
return { fee: feeRate * bytesAccum }
}