All files / src network.ts

81.94% Statements 313/382
75.52% Branches 108/143
82.88% Functions 121/146
81.79% Lines 310/379

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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 13211x 1x   1x 1x 1x 1x 1x 1x                                             1x 1x 1x 1x           1x                                       1x                                             3x 3x 3x 3x   3x 3x 3x 3x             47x 47x   47x     47x 4x 43x 43x       47x             18x                       1x   1x     1x   1x 1x   1x         1x 1x   1x       1x                         1x   1x     1x   1x   1x     1x     1x       1x                       13x   13x   1x   12x   12x 12x   12x         12x       12x   7x 7x 1x     12x                       7x   7x   1x   6x   6x   6x     6x       6x   1x 1x       6x                                 13x 1x                             7x 1x                     4x                   3x 3x 3x 3x                       9x         9x     9x       9x 9x   7x 6x     9x   9x                       11x 11x 11x   11x 2x 9x     9x       9x       9x 6x   3x                       13x   13x 5x 8x 1x   7x             7x           7x                             2x   2x 2x   2x 2x 2x 1x   1x                                     2x   2x 1x 1x     1x       1x         1x                             2x 2x   2x 1x 1x     1x       1x       1x 1x 1x 1x 1x                                 2x 2x   2x 1x 1x     1x       1x       1x 1x 1x 1x 1x                         2x   2x 1x 1x     1x       1x     1x                             2x   2x   1x 1x     1x       2x     2x 2x 1x   2x                                       7x         7x           7x 7x   7x 4x   3x                                                             5x         5x         5x 2x                     3x   3x           3x                                                 5x 1x         4x                       2x         2x   2x         2x   2x                 2x 2x   2x 1x   1x                                                                                                     5x 1x 1x     4x 1x 1x     3x 1x 1x     2x           2x   2x             48x 48x 48x                           47x   47x 47x 2x         47x 47x   103x 4x     103x       47x                               1x   1x   1x 1x 1x 1x           1x   1x 1x 3x 3x 3x 1x   2x     3x 1x   2x       2x 2x       2x           2x               2x 2x             14x 14x 14x                     13x       47x             1x     1x                     1x               2x 2x 2x 2x                                                                                                                                                               2x         2x         2x   2x   2x             1x   2x 2x         2x 2x 2x                           1x       1x 1x       1x 1x           1x       1x 1x 1x       2x 2x   2x 1x   1x   1x 1x       1x 1x 1x 1x                           1x       2x 2x       13x 13x 13x       47x   47x           47x     47x 47x   101x           101x                                   2x 2x 2x           2x 2x   2x 1x       1x   1x                       1x                   1x                         1x             1x                
import { TxOutput, address as bjsAddress, networks, crypto as bjsCrypto, Transaction, payments, Network } from 'bitcoinjs-lib'
import * as FormData from 'form-data'
// @ts-ignore
import * as BN from 'bn.js'
import * as RIPEMD160 from 'ripemd160'
import { MissingParameterError, RemoteServiceError } from './errors'
import { Logger } from './logger'
import { config } from './config'
import { fetchPrivate } from './fetchUtil'
 
export interface UTXO {
  value?: number;
  confirmations?: number;
  tx_hash: string;
  tx_output_n: number;
}
 
export interface PriceInfo {
  units: string;
  amount: BN;
}
 
export interface AccountTokens {
  tokens: string[];
}
 
export interface TransactionInfo {
  block_height: number;
  [key: string]: any;
}
 
const SATOSHIS_PER_BTC = 1e8
const TX_BROADCAST_SERVICE_ZONE_FILE_ENDPOINT = 'zone-file'
const TX_BROADCAST_SERVICE_REGISTRATION_ENDPOINT = 'registration'
const TX_BROADCAST_SERVICE_TX_ENDPOINT = 'transaction'
 
/**
 * @private
 * @ignore
 */
export class BitcoinNetwork {
  broadcastTransaction(transaction: string): Promise<any> {
    return Promise.reject(new Error(`Not implemented, broadcastTransaction(${transaction})`))
  }
 
  getBlockHeight(): Promise<number> {
    return Promise.reject(new Error('Not implemented, getBlockHeight()'))
  }
 
  getTransactionInfo(txid: string): Promise<TransactionInfo> {
    return Promise.reject(new Error(`Not implemented, getTransactionInfo(${txid})`))
  }
 
  getNetworkedUTXOs(address: string): Promise<UTXO[]> {
    return Promise.reject(new Error(`Not implemented, getNetworkedUTXOs(${address})`))
  }
}
/**
 * Use the methods in class to build third-party wallets or in DApps that register names. 
 */
export class BlockstackNetwork {
  blockstackAPIUrl: string
 
  broadcastServiceUrl: string
 
  /**
   * @ignore
   */
  layer1: Network
 
  DUST_MINIMUM: number
 
  includeUtxoMap: {[address: string]: UTXO[]}
 
  excludeUtxoSet: UTXO[]
 
  btc: BitcoinNetwork
 
  MAGIC_BYTES: string
 
  constructor(apiUrl: string, broadcastServiceUrl: string,
              bitcoinAPI: BitcoinNetwork,
              network = networks.bitcoin) {
    this.blockstackAPIUrl = apiUrl
    this.broadcastServiceUrl = broadcastServiceUrl
    this.layer1 = network
    this.btc = bitcoinAPI
 
    this.DUST_MINIMUM = 5500
    this.includeUtxoMap = {}
    this.excludeUtxoSet = []
    this.MAGIC_BYTES = 'id'
  }
 
  /**
   * @ignore
   */
  coerceAddress(address: string) {
    const { hash, version } = bjsAddress.fromBase58Check(address)
    const scriptHashes = [networks.bitcoin.scriptHash,
                          networks.testnet.scriptHash]
    const pubKeyHashes = [networks.bitcoin.pubKeyHash,
                          networks.testnet.pubKeyHash]
    let coercedVersion
    if (scriptHashes.indexOf(version) >= 0) {
      coercedVersion = this.layer1.scriptHash
    } else Eif (pubKeyHashes.indexOf(version) >= 0) {
      coercedVersion = this.layer1.pubKeyHash
    } else {
      throw new Error(`Unrecognized address version number ${version} in ${address}`)
    }
    return bjsAddress.toBase58Check(hash, coercedVersion)
  }
 
  /**
   * This is intended for use in third-party wallets or in DApps that register names.
   */
  getDefaultBurnAddress() {
    return this.coerceAddress('1111111111111111111114oLvT2')
  }
 
  /**
   * Get the price of a name via the legacy /v1/prices API endpoint. This is 
   * intended for use in third-party wallets or in DApps that register names.
   * @param fullyQualifiedName the name to query
   * @return a promise to an Object with { units: String, amount: BigInteger }
   * @private
   */
  getNamePriceV1(fullyQualifiedName: string): Promise<PriceInfo> {
    // legacy code path
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/prices/names/${fullyQualifiedName}`)
      .then((resp) => {
        Iif (!resp.ok) {
          throw new Error(`Failed to query name price for ${fullyQualifiedName}`)
        }
        return resp
      })
      .then(resp => resp.json())
      .then(resp => resp.name_price)
      .then((namePrice) => {
        Iif (!namePrice || !namePrice.satoshis) {
          throw new Error(
            `Failed to get price for ${fullyQualifiedName}. Does the namespace exist?`
          )
        }
        Eif (namePrice.satoshis < this.DUST_MINIMUM) {
          namePrice.satoshis = this.DUST_MINIMUM
        }
        const result = {
          units: 'BTC',
          amount: new BN(String(namePrice.satoshis))
        }
        return result
      })
  }
 
  /**
   * Get the price of a namespace via the legacy /v1/prices API endpoint. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * @param namespaceID the namespace to query
   * @return a promise to an Object with { units: String, amount: BigInteger }
   * @private
   */
  getNamespacePriceV1(namespaceID: string): Promise<PriceInfo> {
    // legacy code path
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/prices/namespaces/${namespaceID}`)
      .then((resp) => {
        Iif (!resp.ok) {
          throw new Error(`Failed to query name price for ${namespaceID}`)
        }
        return resp
      })
      .then(resp => resp.json())
      .then((namespacePrice) => {
        Iif (!namespacePrice || !namespacePrice.satoshis) {
          throw new Error(`Failed to get price for ${namespaceID}`)
        }
        Iif (namespacePrice.satoshis < this.DUST_MINIMUM) {
          namespacePrice.satoshis = this.DUST_MINIMUM
        }
        const result = {
          units: 'BTC',
          amount: new BN(String(namespacePrice.satoshis))
        }
        return result
      })
  }
  
  /**
   * Get the price of a name via the /v2/prices API endpoint. This is intended 
   * for use in third-party wallets or in DApps that register names.
   * @param fullyQualifiedName the name to query
   * @return a promise to an Object with { units: String, amount: BigInteger }
   * @private
   */
  getNamePriceV2(fullyQualifiedName: string): Promise<PriceInfo> {
    return fetchPrivate(`${this.blockstackAPIUrl}/v2/prices/names/${fullyQualifiedName}`)
      .then((resp) => {
        if (resp.status !== 200) {
          // old core node 
          throw new Error('The upstream node does not handle the /v2/ price namespace')
        }
        return resp
      })
      .then(resp => resp.json())
      .then(resp => resp.name_price)
      .then((namePrice) => {
        Iif (!namePrice) {
          throw new Error(
            `Failed to get price for ${fullyQualifiedName}. Does the namespace exist?`
          )
        }
        const result = {
          units: namePrice.units,
          amount: new BN(namePrice.amount)
        }
        if (namePrice.units === 'BTC') {
          // must be at least dust-minimum
          const dustMin = new BN(String(this.DUST_MINIMUM))
          if (result.amount.ucmp(dustMin) < 0) {
            result.amount = dustMin
          }
        }
        return result
      })
  }
 
  /**
   * Get the price of a namespace via the /v2/prices API endpoint.
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param namespaceID the namespace to query
   * @return a promise to an Object with { units: String, amount: BigInteger }
   * @private
   */
  getNamespacePriceV2(namespaceID: string): Promise<PriceInfo> {
    return fetchPrivate(`${this.blockstackAPIUrl}/v2/prices/namespaces/${namespaceID}`)
      .then((resp) => {
        if (resp.status !== 200) {
          // old core node 
          throw new Error('The upstream node does not handle the /v2/ price namespace')
        }
        return resp
      })
      .then(resp => resp.json())
      .then((namespacePrice) => {
        Iif (!namespacePrice) {
          throw new Error(`Failed to get price for ${namespaceID}`)
        }
        const result = {
          units: namespacePrice.units,
          amount: new BN(namespacePrice.amount)
        }
        if (namespacePrice.units === 'BTC') {
          // must be at least dust-minimum
          const dustMin = new BN(String(this.DUST_MINIMUM))
          Iif (result.amount.ucmp(dustMin) < 0) {
            result.amount = dustMin
          }
        }
        return result
      })
  }
 
  /**
   * Get the price of a name. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param fullyQualifiedName the name to query
   * @return a promise to an Object with { units: String, amount: BigInteger }, where
   *   .units encodes the cryptocurrency units to pay (e.g. BTC, STACKS), and
   *   .amount encodes the number of units, in the smallest denominiated amount
   *   (e.g. if .units is BTC, .amount will be satoshis; if .units is STACKS, 
   *   .amount will be microStacks)
   */
  getNamePrice(fullyQualifiedName: string): Promise<PriceInfo> {
    // handle v1 or v2 
    return Promise.resolve().then(() => this.getNamePriceV2(fullyQualifiedName))
      .catch(() => this.getNamePriceV1(fullyQualifiedName))
  }
 
  /**
   * Get the price of a namespace. This is intended for use in third-party 
   * wallets or in DApps that register names.
   * @param namespaceID the namespace to query
   * @return a promise to an Object with { units: String, amount: BigInteger }, where
   *   .units encodes the cryptocurrency units to pay (e.g. BTC, STACKS), and
   *   .amount encodes the number of units, in the smallest denominiated amount
   *   (e.g. if .units is BTC, .amount will be satoshis; if .units is STACKS, 
   *   .amount will be microStacks)
   */
  getNamespacePrice(namespaceID: string): Promise<PriceInfo> {
    // handle v1 or v2 
    return Promise.resolve().then(() => this.getNamespacePriceV2(namespaceID))
      .catch(() => this.getNamespacePriceV1(namespaceID))
  }
 
  /**
   * How many blocks can pass between a name expiring and the name being able to be
   * re-registered by a different owner. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * @param fullyQualifiedName unused
   * @return a promise to the number of blocks
   */
  getGracePeriod(fullyQualifiedName?: string) {
    return Promise.resolve(5000)
  }
 
  /**
   * Get the names -- both on-chain and off-chain -- owned by an address. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * @param address the blockchain address (the hash of the owner public key)
   * @return a promise that resolves to a list of names (Strings)
   */
  getNamesOwned(address: string): Promise<string[]> {
    const networkAddress = this.coerceAddress(address)
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/addresses/bitcoin/${networkAddress}`)
      .then(resp => resp.json())
      .then(obj => obj.names)
  }
 
  /**
   * Get the blockchain address to which a name's registration fee must be sent
   * (the address will depend on the namespace in which it is registered.) 
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param namespace the namespace ID
   * @return a promise that resolves to an address (String)
   */
  getNamespaceBurnAddress(namespace: string): Promise<string> {
    return Promise.all([
      fetchPrivate(`${this.blockstackAPIUrl}/v1/namespaces/${namespace}`),
      this.getBlockHeight()
    ])
      .then(([resp, blockHeight]) => {
        Iif (resp.status === 404) {
          throw new Error(`No such namespace '${namespace}'`)
        } else {
          return Promise.all([resp.json(), blockHeight])
        }
      })
      .then(([namespaceInfo, blockHeight]) => {
        let address = this.getDefaultBurnAddress()
        if (namespaceInfo.version === 2) {
          // pay-to-namespace-creator if this namespace is less than 1 year old
          if (namespaceInfo.reveal_block + 52595 >= blockHeight) {
            address = namespaceInfo.address
          }
        }
        return address
      })
      .then(address => this.coerceAddress(address))
  }
 
  /**
   * Get WHOIS-like information for a name, including the address that owns it,
   * the block at which it expires, and the zone file anchored to it (if available).
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param fullyQualifiedName the name to query.  Can be on-chain of off-chain.
   * @return a promise that resolves to the WHOIS-like information 
   */
  getNameInfo(fullyQualifiedName: string) {
    Logger.debug(this.blockstackAPIUrl)
    const nameLookupURL = `${this.blockstackAPIUrl}/v1/names/${fullyQualifiedName}`
    return fetchPrivate(nameLookupURL)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Name not found')
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((nameInfo) => {
        Logger.debug(`nameInfo: ${JSON.stringify(nameInfo)}`)
        // the returned address _should_ be in the correct network ---
        //  blockstackd gets into trouble because it tries to coerce back to mainnet
        //  and the regtest transaction generation libraries want to use testnet addresses
        if (nameInfo.address) {
          return Object.assign({}, nameInfo, { address: this.coerceAddress(nameInfo.address) })
        } else {
          return nameInfo
        }
      })
  }
 
  /**
   * Get the pricing parameters and creation history of a namespace. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * @param namespaceID the namespace to query
   * @return a promise that resolves to the namespace information.
   */
  getNamespaceInfo(namespaceID: string) {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/namespaces/${namespaceID}`)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Namespace not found')
        } else if (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((namespaceInfo) => {
        // the returned address _should_ be in the correct network ---
        //  blockstackd gets into trouble because it tries to coerce back to mainnet
        //  and the regtest transaction generation libraries want to use testnet addresses
        Iif (namespaceInfo.address && namespaceInfo.recipient_address) {
          return Object.assign({}, namespaceInfo, {
            address: this.coerceAddress(namespaceInfo.address),
            recipient_address: this.coerceAddress(namespaceInfo.recipient_address)
          })
        } else {
          return namespaceInfo
        }
      })
  }
 
  /**
   * Get a zone file, given its hash.  Throws an exception if the zone file
   * obtained does not match the hash. 
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * 
   * @param zonefileHash the ripemd160(sha256) hash of the zone file
   * @return a promise that resolves to the zone file's text
   */
  getZonefile(zonefileHash: string): Promise<string> {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/zonefiles/${zonefileHash}`)
      .then((resp) => {
        Eif (resp.status === 200) {
          return resp.text()
            .then((body) => {
              const sha256 = bjsCrypto.sha256(Buffer.from(body))
              const h = (new RIPEMD160()).update(sha256).digest('hex')
              if (h !== zonefileHash) {
                throw new Error(`Zone file contents hash to ${h}, not ${zonefileHash}`)
              }
              return body
            })
        } else {
          throw new Error(`Bad response status: ${resp.status}`)
        }
      })
  }
 
  /**
   * Get the status of an account for a particular token holding.  This includes its total number of
   * expenditures and credits, lockup times, last `txid`, and so on. 
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param address the account
   * @param tokenType the token type to query
   * @return a promise that resolves to an object representing the state of the account
   *   for this token
   */
  getAccountStatus(address: string, tokenType: string) {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/accounts/${address}/${tokenType}/status`)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Account not found')
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      }).then((accountStatus) => {
        // coerce all addresses, and convert credit/debit to biginteger
        const formattedStatus = Object.assign({}, accountStatus, {
          address: this.coerceAddress(accountStatus.address),
          debit_value: new BN(String(accountStatus.debit_value)),
          credit_value: new BN(String(accountStatus.credit_value))
        })
        return formattedStatus
      })
  }
  
  
  /**
   * Get a page of an account's transaction history. This is intended for use in 
   * third-party wallets or in DApps that register names.
   * @param address the account's address
   * @param page the page number.  Page 0 is the most recent transactions
   * @return a promise that resolves to an Array of Objects, where each Object encodes
   *   states of the account at various block heights (e.g. prior balances, txids, etc)
   */
  getAccountHistoryPage(address: string,
                        page: number): Promise<any[]> {
    const url = `${this.blockstackAPIUrl}/v1/accounts/${address}/history?page=${page}`
    return fetchPrivate(url)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Account not found')
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((historyList) => {
        Iif (historyList.error) {
          throw new Error(`Unable to get account history page: ${historyList.error}`)
        }
        // coerse all addresses and convert to bigint
        return historyList.map((histEntry: any) => {
          histEntry.address = this.coerceAddress(histEntry.address)
          histEntry.debit_value = new BN(String(histEntry.debit_value))
          histEntry.credit_value = new BN(String(histEntry.credit_value))
          return histEntry
        })
      })
  }
 
  /**
   * Get the state(s) of an account at a particular block height.  This includes the state of the
   * account beginning with this block's transactions, as well as all of the states the account
   * passed through when this block was processed (if any).
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param address the account's address
   * @param blockHeight the block to query
   * @return a promise that resolves to an Array of Objects, where each Object encodes
   *   states of the account at this block.
   */
  getAccountAt(address: string, blockHeight: number): Promise<any[]> {
    const url = `${this.blockstackAPIUrl}/v1/accounts/${address}/history/${blockHeight}`
    return fetchPrivate(url)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Account not found')
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((historyList) => {
        Iif (historyList.error) {
          throw new Error(`Unable to get historic account state: ${historyList.error}`)
        }
        // coerce all addresses 
        return historyList.map((histEntry: any) => {
          histEntry.address = this.coerceAddress(histEntry.address)
          histEntry.debit_value = new BN(String(histEntry.debit_value))
          histEntry.credit_value = new BN(String(histEntry.credit_value))
          return histEntry
        })
      })
  }
 
  /**
   * Get the set of token types that this account owns. This is intended for use 
   * in third-party wallets or in DApps that register names.
   * @param address the account's address
   * @return a promise that resolves to an Array of Strings, where each item encodes the 
   *   type of token this account holds (excluding the underlying blockchain's tokens)
   */
  getAccountTokens(address: string): Promise<AccountTokens> {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/accounts/${address}/tokens`)
      .then((resp) => {
        if (resp.status === 404) {
          throw new Error('Account not found')
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((tokenList) => {
        Iif (tokenList.error) {
          throw new Error(`Unable to get token list: ${tokenList.error}`)
        }
        return tokenList
      })
  }
 
  /**
   * Get the number of tokens owned by an account.  If the account does not exist or has no
   * tokens of this type, then 0 will be returned. 
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param address the account's address
   * @param tokenType the type of token to query.
   * @return a promise that resolves to a BigInteger that encodes the number of tokens 
   *   held by this account.
   */
  getAccountBalance(address: string, tokenType: string): Promise<BN> {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/accounts/${address}/${tokenType}/balance`)
      .then((resp) => {
        if (resp.status === 404) {
          // talking to an older blockstack core node without the accounts API
          return Promise.resolve().then(() => new BN('0'))
        } else Iif (resp.status !== 200) {
          throw new Error(`Bad response status: ${resp.status}`)
        } else {
          return resp.json()
        }
      })
      .then((tokenBalance) => {
        Iif (tokenBalance.error) {
          throw new Error(`Unable to get account balance: ${tokenBalance.error}`)
        }
        let balance = '0'
        if (tokenBalance && tokenBalance.balance) {
          balance = tokenBalance.balance
        }
        return new BN(balance)
      })
  }
 
 
  /**
   * Performs a POST request to the given URL. This is intended for 
   * use in third-party wallets or in DApps that register names.
   * @param endpoint  the name of
   * @param body [description]
   * @return Returns a `Promise` that resolves to the object requested.
   * In the event of an error, it rejects with:
   * * a `RemoteServiceError` if there is a problem
   * with the transaction broadcast service
   * * `MissingParameterError` if you call the function without a required
   * parameter
   *
   * @private
   */
  broadcastServiceFetchHelper(endpoint: string, body: any): Promise<any|Error> {
    const requestHeaders = {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    }
 
    const options = {
      method: 'POST',
      headers: requestHeaders,
      body: JSON.stringify(body)
    }
 
    const url = `${this.broadcastServiceUrl}/v1/broadcast/${endpoint}`
    return fetchPrivate(url, options)
      .then((response) => {
        if (response.ok) {
          return response.json()
        } else {
          throw new RemoteServiceError(response)
        }
      })
  }
 
  /**
   * Broadcasts a signed bitcoin transaction to the network optionally waiting to broadcast the
   * transaction until a second transaction has a certain number of confirmations.
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   *
   * @param transaction the hex-encoded transaction to broadcast
   * @param transactionToWatch the hex transaction id of the transaction to watch for
   * the specified number of confirmations before broadcasting the `transaction`
   * @param confirmations the number of confirmations `transactionToWatch` must have
   * before broadcasting `transaction`.
   * @return Returns a Promise that resolves to an object with a
   * `transaction_hash` key containing the transaction hash of the broadcasted transaction.
   *
   * In the event of an error, it rejects with:
   * * a `RemoteServiceError` if there is a problem
   *   with the transaction broadcast service
   * * `MissingParameterError` if you call the function without a required
   *   parameter
   * @private
   */
  broadcastTransaction(
    transaction: string,
    transactionToWatch: string = null,
    confirmations: number = 6
  ) {
    Iif (!transaction) {
      const error = new MissingParameterError('transaction')
      return Promise.reject(error)
    }
 
    Iif (!confirmations && confirmations !== 0) {
      const error = new MissingParameterError('confirmations')
      return Promise.reject(error)
    }
 
    if (transactionToWatch === null) {
      return this.btc.broadcastTransaction(transaction)
    } else {
      /*
       * POST /v1/broadcast/transaction
       * Request body:
       * JSON.stringify({
       *  transaction,
       *  transactionToWatch,
       *  confirmations
       * })
       */
      const endpoint = TX_BROADCAST_SERVICE_TX_ENDPOINT
 
      const requestBody = {
        transaction,
        transactionToWatch,
        confirmations
      }
 
      return this.broadcastServiceFetchHelper(endpoint, requestBody)
    }
  }
 
  /**
   * Broadcasts a zone file to the Atlas network via the transaction broadcast service.
   * This is intended for use in third-party wallets or in DApps that register names.
   *
   * @param zoneFile the zone file to be broadcast to the Atlas network
   * @param transactionToWatch the hex transaction id of the transaction
   * to watch for confirmation before broadcasting the zone file to the Atlas network
   * @return Returns a Promise that resolves to an object with a
   * `transaction_hash` key containing the transaction hash of the broadcasted transaction.
   *
   * In the event of an error, it rejects with:
   * * a `RemoteServiceError` if there is a problem
   *   with the transaction broadcast service
   * * `MissingParameterError` if you call the function without a required
   *   parameter
   * @private
   */
  broadcastZoneFile(
    zoneFile?: string,
    transactionToWatch: string = null
  ) {
    if (!zoneFile) {
      return Promise.reject(new MissingParameterError('zoneFile'))
    }
 
    // TODO: validate zonefile
 
    if (transactionToWatch) {
      // broadcast via transaction broadcast service
 
      /*
       * POST /v1/broadcast/zone-file
       * Request body:
       * JSON.stringify({
       *  zoneFile,
       *  transactionToWatch
       * })
       */
 
      const requestBody = {
        zoneFile,
        transactionToWatch
      }
 
      const endpoint = TX_BROADCAST_SERVICE_ZONE_FILE_ENDPOINT
 
      return this.broadcastServiceFetchHelper(endpoint, requestBody)
    } else {
      // broadcast via core endpoint
 
      // zone file is two words but core's api treats it as one word 'zonefile'
      const requestBody = { zonefile: zoneFile }
 
      return fetchPrivate(`${this.blockstackAPIUrl}/v1/zonefile/`,
                          {
                            method: 'POST',
                            body: JSON.stringify(requestBody),
                            headers: {
                              'Content-Type': 'application/json'
                            }
                          })
        .then((resp) => {
          const json = resp.json()
          return json
            .then((respObj) => {
              if (respObj.hasOwnProperty('error')) {
                throw new RemoteServiceError(resp)
              }
              return respObj.servers
            })
        })
    }
  }
 
  /**
   * Sends the preorder and registration transactions and zone file
   * for a Blockstack name registration along with the to the transaction
   *  broadcast service.
   *
   * The transaction broadcast:
   *
   * * immediately broadcasts the preorder transaction
   * * broadcasts the register transactions after the preorder transaction
   * has an appropriate number of confirmations
   * * broadcasts the zone file to the Atlas network after the register transaction
   * has an appropriate number of confirmations
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   *
   * @param preorderTransaction the hex-encoded, signed preorder transaction generated
   * using the `makePreorder` function
   * @param registerTransaction the hex-encoded, signed register transaction generated
   * using the `makeRegister` function
   * @param zoneFile the zone file to be broadcast to the Atlas network
   * @return Returns a Promise that resolves to an object with a
   * `transaction_hash` key containing the transaction hash of the broadcasted transaction.
   *
   * In the event of an error, it rejects with:
   * * a `RemoteServiceError` if there is a problem
   *   with the transaction broadcast service
   * * `MissingParameterError` if you call the function without a required
   *   parameter
   * @private
   */
  broadcastNameRegistration(
    preorderTransaction: string,
    registerTransaction: string,
    zoneFile: string
  ) {
    /*
       * POST /v1/broadcast/registration
       * Request body:
       * JSON.stringify({
       * preorderTransaction,
       * registerTransaction,
       * zoneFile
       * })
       */
 
    if (!preorderTransaction) {
      const error = new MissingParameterError('preorderTransaction')
      return Promise.reject(error)
    }
 
    if (!registerTransaction) {
      const error = new MissingParameterError('registerTransaction')
      return Promise.reject(error)
    }
 
    if (!zoneFile) {
      const error = new MissingParameterError('zoneFile')
      return Promise.reject(error)
    }
 
    const requestBody = {
      preorderTransaction,
      registerTransaction,
      zoneFile
    }
 
    const endpoint = TX_BROADCAST_SERVICE_REGISTRATION_ENDPOINT
 
    return this.broadcastServiceFetchHelper(endpoint, requestBody)
  }
 
  /**
   * @ignore
   */
  getFeeRate(): Promise<number> {
    return fetchPrivate('https://bitcoinfees.earn.com/api/v1/fees/recommended')
      .then(resp => resp.json())
      .then(rates => Math.floor(rates.fastestFee))
  }
 
  /**
   * @ignore
   */
  countDustOutputs() {
    throw new Error('Not implemented.')
  }
 
  /**
   * @ignore
   */
  getUTXOs(address: string): Promise<UTXO[]> {
    return this.getNetworkedUTXOs(address)
      .then((networkedUTXOs) => {
        let returnSet = networkedUTXOs.concat()
        if (this.includeUtxoMap.hasOwnProperty(address)) {
          returnSet = networkedUTXOs.concat(this.includeUtxoMap[address])
        }
 
        // aaron: I am *well* aware this is O(n)*O(m) runtime
        //    however, clients should clear the exclude set periodically
        const excludeSet = this.excludeUtxoSet
        returnSet = returnSet.filter(
          (utxo) => {
            const inExcludeSet = excludeSet.reduce(
              (inSet, utxoToCheck) => inSet || (utxoToCheck.tx_hash === utxo.tx_hash
                          && utxoToCheck.tx_output_n === utxo.tx_output_n), false
            )
            return !inExcludeSet
          }
        )
 
        return returnSet
      })
  }
 
  /**
   * This will modify the network's utxo set to include UTXOs
   *  from the given transaction and exclude UTXOs *spent* in
   *  that transaction. 
   * 
   * This is intended for use in third-party wallets or in DApps that register names.
   * @param txHex - the hex-encoded transaction to use
   * @return no return value, this modifies the UTXO config state
   * @private
   * @ignore
   */
  modifyUTXOSetFrom(txHex: string) {
    const tx = Transaction.fromHex(txHex)
 
    const excludeSet: UTXO[] = this.excludeUtxoSet.concat()
 
    tx.ins.forEach((utxoUsed) => {
      const reverseHash = Buffer.from(utxoUsed.hash)
      reverseHash.reverse()
      excludeSet.push({
        tx_hash: reverseHash.toString('hex'),
        tx_output_n: utxoUsed.index
      })
    })
 
    this.excludeUtxoSet = excludeSet
 
    const txHash = Buffer.from(tx.getHash().reverse()).toString('hex')
    tx.outs.forEach((utxoCreated, txOutputN) => {
      const isNullData = function isNullData(script: Buffer) {
        try {
          payments.embed({ output: script }, { validate: true })
          return true
        } catch (_) {
          return false
        }
      }
      if (isNullData(utxoCreated.script)) {
        return
      }
      const address = bjsAddress.fromOutputScript(
        utxoCreated.script, this.layer1
      )
 
      let includeSet: UTXO[] = []
      Iif (this.includeUtxoMap.hasOwnProperty(address)) {
        includeSet = includeSet.concat(this.includeUtxoMap[address])
      }
 
      includeSet.push({
        tx_hash: txHash,
        confirmations: 0,
        value: (utxoCreated as TxOutput).value,
        tx_output_n: txOutputN
      })
      this.includeUtxoMap[address] = includeSet
    })
  }
 
  /**
   * @ignore
   */
  resetUTXOs(address: string) {
    delete this.includeUtxoMap[address]
    this.excludeUtxoSet = []
  }
 
  /**
   * @ignore
   */
  getConsensusHash() {
    return fetchPrivate(`${this.blockstackAPIUrl}/v1/blockchains/bitcoin/consensus`)
      .then(resp => resp.json())
      .then(x => x.consensus_hash)
  }
 
  getTransactionInfo(txHash: string): Promise<TransactionInfo> {
    return this.btc.getTransactionInfo(txHash)
  }
 
  /**
   * @ignore
   */
  getBlockHeight() {
    return this.btc.getBlockHeight()
  }
 
  getNetworkedUTXOs(address: string): Promise<UTXO[]> {
    return this.btc.getNetworkedUTXOs(address)
  }
}
 
/**
 * @ignore
 */
export class LocalRegtest extends BlockstackNetwork {
  constructor(apiUrl: string, broadcastServiceUrl: string,
              bitcoinAPI: BitcoinNetwork) {
    super(apiUrl, broadcastServiceUrl, bitcoinAPI, networks.testnet)
  }
 
  getFeeRate(): Promise<number> {
    return Promise.resolve(Math.floor(0.00001000 * SATOSHIS_PER_BTC))
  }
}
 
/**
 * @ignore
 */
export class BitcoindAPI extends BitcoinNetwork {
  bitcoindUrl: string
 
  bitcoindCredentials: {username: string, password: string}
 
  importedBefore: any
 
  constructor(bitcoindUrl: string, bitcoindCredentials: {username: string, password: string}) {
    super()
    this.bitcoindUrl = bitcoindUrl
    this.bitcoindCredentials = bitcoindCredentials
    this.importedBefore = {}
  }
 
  broadcastTransaction(transaction: string) {
    const jsonRPC = {
      jsonrpc: '1.0',
      method: 'sendrawtransaction',
      params: [transaction]
    }
    const authString =      Buffer.from(`${this.bitcoindCredentials.username}:${this.bitcoindCredentials.password}`)
      .toString('base64')
    const headers = { Authorization: `Basic ${authString}` }
    return fetchPrivate(this.bitcoindUrl, {
      method: 'POST',
      body: JSON.stringify(jsonRPC),
      headers
    })
      .then(resp => resp.json())
      .then(respObj => respObj.result)
  }
 
  getBlockHeight() {
    const jsonRPC = {
      jsonrpc: '1.0',
      method: 'getblockcount'
    }
    const authString =      Buffer.from(`${this.bitcoindCredentials.username}:${this.bitcoindCredentials.password}`)
      .toString('base64')
    const headers = { Authorization: `Basic ${authString}` }
    return fetchPrivate(this.bitcoindUrl, {
      method: 'POST',
      body: JSON.stringify(jsonRPC),
      headers
    })
      .then(resp => resp.json())
      .then(respObj => respObj.result)
  }
 
  getTransactionInfo(txHash: string): Promise<TransactionInfo> {
    const jsonRPC = {
      jsonrpc: '1.0',
      method: 'gettransaction',
      params: [txHash]
    }
    const authString =      Buffer.from(`${this.bitcoindCredentials.username}:${this.bitcoindCredentials.password}`)
      .toString('base64')
    const headers = { Authorization: `Basic ${authString}` }
    return fetchPrivate(this.bitcoindUrl, {
      method: 'POST',
      body: JSON.stringify(jsonRPC),
      headers
    })
      .then(resp => resp.json())
      .then(respObj => respObj.result)
      .then(txInfo => txInfo.blockhash)
      .then((blockhash) => {
        const jsonRPCBlock = {
          jsonrpc: '1.0',
          method: 'getblockheader',
          params: [blockhash]
        }
        headers.Authorization = `Basic ${authString}`
        return fetchPrivate(this.bitcoindUrl, {
          method: 'POST',
          body: JSON.stringify(jsonRPCBlock),
          headers
        })
      })
      .then(resp => resp.json())
      .then((respObj) => {
        if (!respObj || !respObj.result) {
          // unconfirmed 
          throw new Error('Unconfirmed transaction')
        } else {
          return { block_height: respObj.result.height }
        }
      })
  }
 
  getNetworkedUTXOs(address: string): Promise<UTXO[]> {
    const jsonRPCImport = {
      jsonrpc: '1.0',
      method: 'importaddress',
      params: [address]
    }
    const jsonRPCUnspent = {
      jsonrpc: '1.0',
      method: 'listunspent',
      params: [0, 9999999, [address]]
    }
    const authString = Buffer.from(`${this.bitcoindCredentials.username}:${this.bitcoindCredentials.password}`)
      .toString('base64')
    const headers = { Authorization: `Basic ${authString}` }
 
    const importPromise = (this.importedBefore[address])
      ? Promise.resolve()
      : fetchPrivate(this.bitcoindUrl, {
        method: 'POST',
        body: JSON.stringify(jsonRPCImport),
        headers
      })
        .then(() => { this.importedBefore[address] = true })
 
    return importPromise
      .then(() => fetchPrivate(this.bitcoindUrl, {
        method: 'POST',
        body: JSON.stringify(jsonRPCUnspent),
        headers
      }))
      .then(resp => resp.json())
      .then(x => x.result)
      .then(utxos => utxos.map(
        (x: any) => ({
          value: Math.round(x.amount * SATOSHIS_PER_BTC),
          confirmations: x.confirmations,
          tx_hash: x.txid,
          tx_output_n: x.vout
        })
      ))
  }
}
 
/**
 * @ignore
 */
export class InsightClient extends BitcoinNetwork {
  apiUrl: string
 
  constructor(insightUrl: string = 'https://utxo.technofractal.com/') {
    super()
    this.apiUrl = insightUrl
  }
 
  broadcastTransaction(transaction: string) {
    const jsonData = { rawtx: transaction }
    return fetchPrivate(`${this.apiUrl}/tx/send`,
                        {
                          method: 'POST',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify(jsonData)
                        })
      .then(resp => resp.json())
  }
 
  getBlockHeight() {
    return fetchPrivate(`${this.apiUrl}/status`)
      .then(resp => resp.json())
      .then(status => status.blocks)
  }
 
  getTransactionInfo(txHash: string): Promise<TransactionInfo> {
    return fetchPrivate(`${this.apiUrl}/tx/${txHash}`)
      .then(resp => resp.json())
      .then((transactionInfo) => {
        if (transactionInfo.error) {
          throw new Error(`Error finding transaction: ${transactionInfo.error}`)
        }
        return fetchPrivate(`${this.apiUrl}/block/${transactionInfo.blockHash}`)
      })
      .then(resp => resp.json())
      .then(blockInfo => ({ block_height: blockInfo.height }))
  }
 
  getNetworkedUTXOs(address: string): Promise<UTXO[]> {
    return fetchPrivate(`${this.apiUrl}/addr/${address}/utxo`)
      .then(resp => resp.json())
      .then(utxos => utxos.map(
        (x: any) => ({
          value: x.satoshis,
          confirmations: x.confirmations,
          tx_hash: x.txid,
          tx_output_n: x.vout
        })
      ))
  }
}
 
 
/**
 * @ignore
 */
export class BlockchainInfoApi extends BitcoinNetwork {
  utxoProviderUrl: string
 
  constructor(blockchainInfoUrl: string = 'https://blockchain.info') {
    super()
    this.utxoProviderUrl = blockchainInfoUrl
  }
 
  getBlockHeight() {
    return fetchPrivate(`${this.utxoProviderUrl}/latestblock?cors=true`)
      .then(resp => resp.json())
      .then(blockObj => blockObj.height)
  }
 
  getNetworkedUTXOs(address: string): Promise<UTXO[]> {
    return fetchPrivate(`${this.utxoProviderUrl}/unspent?format=json&active=${address}&cors=true`)
      .then((resp) => {
        Iif (resp.status === 500) {
          Logger.debug('UTXO provider 500 usually means no UTXOs: returning []')
          return {
            unspent_outputs: []
          }
        } else {
          return resp.json()
        }
      })
      .then(utxoJSON => utxoJSON.unspent_outputs)
      .then(utxoList => utxoList.map(
        (utxo: any) => {
          const utxoOut = {
            value: utxo.value,
            tx_output_n: utxo.tx_output_n,
            confirmations: utxo.confirmations,
            tx_hash: utxo.tx_hash_big_endian
          }
          return utxoOut
        }
      ))
  }
 
  getTransactionInfo(txHash: string): Promise<TransactionInfo> {
    return fetchPrivate(`${this.utxoProviderUrl}/rawtx/${txHash}?cors=true`)
      .then((resp) => {
        if (resp.status === 200) {
          return resp.json()
        } else {
          throw new Error(`Could not lookup transaction info for '${txHash}'. Server error.`)
        }
      })
      .then(respObj => ({ block_height: respObj.block_height }))
  }
 
  broadcastTransaction(transaction: string) {
    const form = new FormData()
    form.append('tx', transaction)
    return fetchPrivate(`${this.utxoProviderUrl}/pushtx?cors=true`,
                        {
                          method: 'POST',
                          body: <any>form
                        })
      .then((resp) => {
        const text = resp.text()
        return text
          .then((respText) => {
            if (respText.toLowerCase().indexOf('transaction submitted') >= 0) {
              const txHash = Buffer.from(
                Transaction.fromHex(transaction)
                  .getHash()
                  .reverse()).toString('hex') // big_endian
              return txHash
            } else {
              throw new RemoteServiceError(resp,
                                           `Broadcast transaction failed with message: ${respText}`)
            }
          })
      })
  }
}
 
 
/**
* @ignore
*/
const LOCAL_REGTEST = new LocalRegtest(
  'http://localhost:16268',
  'http://localhost:16269',
  new BitcoindAPI('http://localhost:18332/',
                  { username: 'blockstack', password: 'blockstacksystem' })
)
 
/**
* Instance of [[BlockstackNetwork]] set to the default endpoints. 
*/
export const MAINNET_DEFAULT = new BlockstackNetwork(
  'https://core.blockstack.org',
  'https://broadcast.blockstack.org',
  new BlockchainInfoApi()
)
 
/**
 * Get WHOIS-like information for a name, including the address that owns it,
 * the block at which it expires, and the zone file anchored to it (if available). 
 * This is intended for use in third-party wallets or in DApps that register names.
 * @param fullyQualifiedName the name to query.  Can be on-chain of off-chain.
 * @return a promise that resolves to the WHOIS-like information 
 */
export function getNameInfo(fullyQualifiedName: string) {
  return config.network.getNameInfo(fullyQualifiedName)
}
 
/**
* @ignore
*/
export const network = {
  BlockstackNetwork,
  LocalRegtest,
  BlockchainInfoApi,
  BitcoindAPI,
  InsightClient,
  defaults: { LOCAL_REGTEST, MAINNET_DEFAULT }
}