All files / src/operations utils.js

97.5% Statements 78/80
93.1% Branches 27/29
100% Functions 22/22
97.26% Lines 71/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193                  1x     19x 19x       8x           1x 1x 1x 1x 1x             260x     260x         564x 542x   22x         186x 260x 564x               186x 186x 170x   186x 186x 186x 186x   186x 186x   186x       62x 62x 29x     182x                             11x 11x 11x 11x 267x     11x 267x     11x                                               68x 2x       66x   66x 66x 58x     139x 66x 34x 34x 34x 34x 31x     34x 34x   50x 32x   32x       32x   32x 32x 27x     32x                 71x 32x 10x 10x     32x 32x 71x 71x     32x    
/* @flow */
 
import bitcoinjs from 'bitcoinjs-lib'
import RIPEMD160 from 'ripemd160'
import bigi from 'bigi'
 
import { NotEnoughFundsError } from '../errors'
import { TransactionSigner } from './signers'
 
export const DUST_MINIMUM = 5500
 
export function hash160(buff: Buffer) {
  const sha256 = bitcoinjs.crypto.sha256(buff)
  return (new RIPEMD160()).update(sha256).digest()
}
 
export function hash128(buff: Buffer) {
  return Buffer.from(bitcoinjs.crypto.sha256(buff).slice(0, 16))
}
 
 
// COPIED FROM coinselect, because 1 byte matters sometimes.
// baseline estimates, used to improve performance
const TX_EMPTY_SIZE = 4 + 1 + 1 + 4
const TX_INPUT_BASE = 32 + 4 + 1 + 4
const TX_INPUT_PUBKEYHASH = 107
const TX_OUTPUT_BASE = 8 + 1
const TX_OUTPUT_PUBKEYHASH = 25
 
type txPoint = {
  script: { length: number }
}
 
function inputBytes(input: txPoint | null) {
  Iif (input && input.script && input.script.length > 0) {
    return TX_INPUT_BASE + input.script.length
  } else {
    return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH
  }
}
 
function outputBytes(output: txPoint | null) {
  if (output && output.script && output.script.length > 0) {
    return TX_OUTPUT_BASE + output.script.length
  } else {
    return TX_OUTPUT_BASE + TX_OUTPUT_PUBKEYHASH
  }
}
 
function transactionBytes(inputs: Array<txPoint | null>, outputs: Array<txPoint | null>) {
  return TX_EMPTY_SIZE
    + inputs.reduce((a: number, x: txPoint | null) => (a + inputBytes(x)), 0)
    + outputs.reduce((a: number, x: txPoint | null) => (a + outputBytes(x)), 0)
}
 
//
 
export function estimateTXBytes(txIn: bitcoinjs.Transaction | bitcoinjs.TransactionBuilder,
                                additionalInputs: number,
                                additionalOutputs: number) {
  let innerTx = txIn
  if (txIn instanceof bitcoinjs.TransactionBuilder) {
    innerTx = txIn.__tx
  }
  const dummyInputs: Array<null> = new Array(additionalInputs)
  dummyInputs.fill(null)
  const dummyOutputs: Array<null> = new Array(additionalOutputs)
  dummyOutputs.fill(null)
 
  const inputs: Array<null | txPoint> = [].concat(innerTx.ins, dummyInputs)
  const outputs: Array<null | txPoint> = [].concat(innerTx.outs, dummyOutputs)
 
  return transactionBytes(inputs, outputs)
}
 
export function sumOutputValues(txIn : bitcoinjs.Transaction | bitcoinjs.TransactionBuilder) {
  let innerTx = txIn
  if (txIn instanceof bitcoinjs.TransactionBuilder) {
    innerTx = txIn.__tx
  }
 
  return innerTx.outs.reduce((agg, x) => agg + x.value, 0)
}
 
export function decodeB40(input: string) {
  // treat input as a base40 integer, and output a hex encoding
  // of that integer.
  //
  //   for each digit of the string, find its location in `characters`
  //    to get the value of the digit, then multiply by 40^(-index in input)
  // e.g.,
  // the 'right-most' character has value: (digit-value) * 40^0
  //  the next character has value: (digit-value) * 40^1
  //
  // hence, we reverse the characters first, and use the index
  //  to compute the value of each digit, then sum
  const characters = '0123456789abcdefghijklmnopqrstuvwxyz-_.+'
  const base = bigi.valueOf(40)
  const inputDigits = input.split('').reverse()
  const digitValues = inputDigits.map(
    ((character: string, exponent: number) => bigi.valueOf(characters.indexOf(character))
      .multiply(base.pow(bigi.valueOf(exponent))))
  )
  const sum = digitValues.reduce(
    (agg: bigi.BigInteger, cur: bigi.BigInteger) => agg.add(cur),
    bigi.ZERO
  )
  return sum.toHex()
}
 
/**
 * Adds UTXOs to fund a transaction
 * @param {TransactionBuilder} txBuilderIn - a transaction builder object to add the inputs to. this
 *    object is _always_ mutated. If not enough UTXOs exist to fund, the tx builder object
 *    will still contain as many inputs as could be found.
 * @param {Array<{value: number, tx_hash: string, tx_output_n}>} utxos - the utxo set for the
 *    payer's address.
 * @param {number} amountToFund - the amount of satoshis to fund in the transaction. the payer's
 *    utxos will be included to fund up to this amount of *output* and the corresponding *fees*
 *    for those additional inputs
 * @param {number} feeRate - the satoshis/byte fee rate to use for fee calculation
 * @param {boolean} fundNewFees - if true, this function will fund `amountToFund` and any new fees
 *    associated with including the new inputs.
 *    if false, this function will fund _at most_ `amountToFund`
 * @returns {number} - the amount of leftover change (in satoshis)
 * @private
 */
export function addUTXOsToFund(txBuilderIn: bitcoinjs.TransactionBuilder,
                               utxos: Array<{value: number, tx_hash: string, tx_output_n: number}>,
                               amountToFund: number, feeRate: number,
                               fundNewFees: ?boolean = true) {
  if (utxos.length === 0) {
    throw new NotEnoughFundsError(amountToFund)
  }
 
  // how much are we increasing fees by adding an input ?
  const newFees = feeRate * (estimateTXBytes(txBuilderIn, 1, 0)
                             - estimateTXBytes(txBuilderIn, 0, 0))
  let utxoThreshhold = amountToFund
  if (fundNewFees) {
    utxoThreshhold += newFees
  }
 
  const goodUtxos = utxos.filter(utxo => utxo.value >= utxoThreshhold)
  if (goodUtxos.length > 0) {
    goodUtxos.sort((a, b) => a.value - b.value)
    const selected = goodUtxos[0]
    let change = selected.value - amountToFund
    if (fundNewFees) {
      change -= newFees
    }
 
    txBuilderIn.addInput(selected.tx_hash, selected.tx_output_n)
    return change
  } else {
    utxos.sort((a, b) => b.value - a.value)
    const largest = utxos[0]
 
    Iif (newFees >= largest.value) {
      throw new NotEnoughFundsError(amountToFund)
    }
 
    txBuilderIn.addInput(largest.tx_hash, largest.tx_output_n)
 
    let remainToFund = amountToFund - largest.value
    if (fundNewFees) {
      remainToFund += newFees
    }
 
    return addUTXOsToFund(txBuilderIn, utxos.slice(1),
                          remainToFund, feeRate, fundNewFees)
  }
}
 
 
export function signInputs(txB: bitcoinjs.TransactionBuilder,
                           defaultSigner: TransactionSigner,
                           otherSigners?: Array<{index: number, signer: TransactionSigner}>) {
  const signerArray = txB.__tx.ins.map(() => defaultSigner)
  if (otherSigners) {
    otherSigners.forEach((signerPair) => {
      signerArray[signerPair.index] = signerPair.signer
    })
  }
  let signingPromise = Promise.resolve()
  for (let i = 0; i < txB.__tx.ins.length; i++) {
    signingPromise = signingPromise.then(
      () => signerArray[i].signTransaction(txB, i)
    )
  }
  return signingPromise.then(() => txB)
}