All files / src/operations utils.ts

97.89% Statements 93/95
92.59% Branches 25/27
100% Functions 24/24
97.73% Lines 86/88

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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230    1x 1x 1x     1x 1x             1x           1x 19x 19x             1x 8x 8x           1x 1x 1x 1x 1x             260x     260x         564x 542x   22x         186x 260x 564x             1x 266x       248x 49x   199x                 1x     186x 186x 186x 186x 186x   186x 186x   186x             1x 62x 182x             1x                       11x 11x 11x 11x 267x     11x 267x     11x                                         1x       68x 2x       66x   66x 66x 58x     139x 66x 34x 34x 34x 34x 31x     34x 34x   50x 32x   32x       32x   32x 32x 27x     32x           1x     32x 71x 32x 10x 10x     32x 32x 71x 71x     32x    
 
 
import { TransactionBuilder, Transaction, TxOutput } from 'bitcoinjs-lib'
import * as BN from 'bn.js'
import { NotEnoughFundsError } from '../errors'
import { TransactionSigner } from './signers'
import { UTXO } from '../network'
import { hashSha256Sync } from '../encryption/sha2Hash'
import { hashRipemd160 } from '../encryption/hashRipemd160'
 
 
/**
 * 
 * @ignore
 */
export const DUST_MINIMUM = 5500
 
/**
 * Creates a RIPEMD160(SHA256(input)) hash.
 * @ignore
 */
export function hash160(buff: Buffer) {
  const sha256 = hashSha256Sync(buff)
  return hashRipemd160(sha256)
}
 
/**
 * Creates a SHA256 hash, truncated to 128 bits. 
 * @ignore
 */
export function hash128(buff: Buffer) {
  const sha256 = hashSha256Sync(buff)
  return sha256.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)
}
 
/**
 * 
 * @ignore
 */
export function getTransactionInsideBuilder(txBuilder: TransactionBuilder) {
  return ((txBuilder as any).__TX as Transaction)
}
 
function getTransaction(txIn: Transaction | TransactionBuilder) {
  if (txIn instanceof Transaction) {
    return txIn
  }
  return getTransactionInsideBuilder(txIn)
}
 
//
 
/**
 * 
 * @ignore
 */
export function estimateTXBytes(txIn: Transaction | TransactionBuilder,
                                additionalInputs: number,
                                additionalOutputs: number) {
  const innerTx = getTransaction(txIn)
  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)
}
 
/**
 * 
 * @ignore
 */
export function sumOutputValues(txIn: Transaction | TransactionBuilder) {
  const innerTx = getTransaction(txIn)
  return innerTx.outs.reduce((agg, x) => agg + (x as TxOutput).value, 0)
}
 
/**
 * 
 * @ignore
 */
export function decodeB40(input: string): 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 = new BN(40)
  const inputDigits = input.split('').reverse()
  const digitValues = inputDigits.map(
    ((character: string, exponent: number) => new BN(characters.indexOf(character))
      .mul(base.pow(new BN(exponent))))
  )
  const sum = digitValues.reduce(
    (agg: BN, cur: BN) => agg.add(cur),
    new BN(0)
  )
  return sum.toString(16, 2)
}
 
/**
 * 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
 * @ignore
 */
export function addUTXOsToFund(txBuilderIn: TransactionBuilder,
                               utxos: Array<UTXO>,
                               amountToFund: number, feeRate: number,
                               fundNewFees: boolean = true): number {
  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: TransactionBuilder,
                           defaultSigner: TransactionSigner,
                           otherSigners?: Array<{index: number, signer: TransactionSigner}>) {
  const txInner = getTransactionInsideBuilder(txB)
  const signerArray = txInner.ins.map(() => defaultSigner)
  if (otherSigners) {
    otherSigners.forEach((signerPair) => {
      signerArray[signerPair.index] = signerPair.signer
    })
  }
  let signingPromise = Promise.resolve()
  for (let i = 0; i < txInner.ins.length; i++) {
    signingPromise = signingPromise.then(
      () => signerArray[i].signTransaction(txB, i)
    )
  }
  return signingPromise.then(() => txB)
}