All files / src utils.ts

73.68% Statements 42/57
82.14% Branches 23/28
85.71% Functions 12/14
72.73% Lines 40/55

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  1x 1x 1x 1x         1x             1x 8x                       1x 7x                       1x 5x                         1x                                     1x   1x             78x 78x   26x         2x     24x               1x                     45x         1x               1x 15x   15x                     1x 88x               1x 20x       20x 620x 620x 620x                       1x 32x 32x   32x 32x                   32x                     1x                  
 
import url from 'url'
import { ECPair, address, crypto } from 'bitcoinjs-lib'
import { config } from './config'
import { Logger } from './logger'
 
/**
 *  @ignore
 */
export const BLOCKSTACK_HANDLER = 'blockstack'
 
/**
 * Time
 * @private
 * @ignore
 */
export function nextYear() {
  return new Date(
    new Date().setFullYear(
      new Date().getFullYear() + 1
    )
  )
}
 
/**
 * Time
 * @private
 * @ignore
 */
export function nextMonth() {
  return new Date(
    new Date().setMonth(
      new Date().getMonth() + 1
    )
  )
}
 
/**
 * Time
 * @private
 * @ignore
 */
export function nextHour() {
  return new Date(
    new Date().setHours(
      new Date().getHours() + 1
    )
  )
}
 
/**
 * Query Strings
 * @private
 * @ignore
 */
 
export function updateQueryStringParameter(uri: string, key: string, value: string) {
  const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i')
  const separator = uri.indexOf('?') !== -1 ? '&' : '?'
  if (uri.match(re)) {
    return uri.replace(re, `$1${key}=${value}$2`)
  } else {
    return `${uri}${separator}${key}=${value}`
  }
}
 
/**
 * Versioning
 * @param {string} v1 - the left half of the version inequality
 * @param {string} v2 - right half of the version inequality
 * @returns {bool} iff v1 >= v2
 * @private
 * @ignore
 */
 
export function isLaterVersion(v1: string, v2: string) {
  if (v1 === undefined) {
    v1 = '0.0.0'
  }
 
  if (v2 === undefined) {
    v2 = '0.0.0'
  }
 
  const v1tuple = v1.split('.').map(x => parseInt(x, 10))
  const v2tuple = v2.split('.').map(x => parseInt(x, 10))
 
  for (let index = 0; index < v2.length; index++) {
    if (index >= v1.length) {
      v2tuple.push(0)
    }
    if (v1tuple[index] < v2tuple[index]) {
      return false
    }
  }
  return true
}
 
/**
 * Time
 * @private
 * @ignore
 */
export function hexStringToECPair(skHex: string) {
  const ecPairOptions = {
    network: config.network.layer1,
    compressed: true
  }
 
  if (skHex.length === 66) {
    if (skHex.slice(64) !== '01') {
      throw new Error('Improperly formatted private-key hex string. 66-length hex usually '
                      + 'indicates compressed key, but last byte must be == 1')
    }
    return ECPair.fromPrivateKey(Buffer.from(skHex.slice(0, 64), 'hex'), ecPairOptions)
  } else if (skHex.length === 64) {
    ecPairOptions.compressed = false
    return ECPair.fromPrivateKey(Buffer.from(skHex, 'hex'), ecPairOptions)
  } else {
    throw new Error('Improperly formatted private-key hex string: length should be 64 or 66.')
  }
}
 
/**
 * 
 * @ignore
 */
export function ecPairToHexString(secretKey: ECPair) {
  const ecPointHex = secretKey.privateKey.toString('hex')
  if (secretKey.compressed) {
    return `${ecPointHex}01`
  } else {
    return ecPointHex
  }
}
 
/**
 * Time
 * @private
 * @ignore
 */
export function ecPairToAddress(keyPair: ECPair) {
  return address.toBase58Check(crypto.hash160(keyPair.publicKey), keyPair.network.pubKeyHash)
}
 
/**
 * UUIDs
 * @private
 * @ignore
 */
export function makeUUID4() {
  let d = new Date().getTime()
  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
    d += performance.now() // use high-precision timer if available
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
}
 
/**
 * Checks if both urls pass the same origin check & are absolute
 * @param  {[type]}  uri1 first uri to check
 * @param  {[type]}  uri2 second uri to check
 * @return {Boolean} true if they pass the same origin check
 * @private
 * @ignore
 */
export function isSameOriginAbsoluteUrl(uri1: string, uri2: string) {
  const parsedUri1 = url.parse(uri1)
  const parsedUri2 = url.parse(uri2)
 
  const port1 = parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80)
  const port2 = parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80)
 
  const match = {
    scheme: parsedUri1.protocol === parsedUri2.protocol,
    hostname: parsedUri1.hostname === parsedUri2.hostname,
    port: port1 === port2,
    absolute: (uri1.includes('http://') || uri1.includes('https://'))
    && (uri2.includes('http://') || uri2.includes('https://'))
  }
 
  return match.scheme && match.hostname && match.port && match.absolute
}
 
/**
 * Runtime check for the existence of the global `window` object and the 
 * given API key (name) on `window`. Throws an error if either are not
 * available in the current environment. 
 * @param fnDesc The function name to include in the thrown error and log.
 * @param name The name of the key on the `window` object to check for.
 * @hidden
 */
export function checkWindowAPI(fnDesc: string, name: string) {
  const api = typeof window !== 'undefined' && window[name]
  if (!api) {
    const errMsg = `\`${fnDesc}\` uses the \`window.${name}\` API which is `
      + ' not available in the current environment.'
    Logger.error(errMsg)
    throw new Error(errMsg)
  }
}