All files / src/operations skeletons.ts

90.41% Statements 245/271
68.42% Branches 65/95
100% Functions 27/27
90.3% Lines 242/268

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    1x 1x 1x     1x                       1x                                   2x     2x       2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x             4x     4x       4x     4x       4x     4x       4x     4x       4x       4x 64x         4x       4x     4x       4x     4x       3x 3x 3x 48x 3x 3x 3x   3x                     15x     15x               44x 44x 44x               44x 44x     44x           1x                                       5x 5x 5x 5x   5x   5x 5x 5x     5x   5x   5x 5x 5x 5x 5x   5x 2x 2x       2x   2x 2x     5x 5x   5x 5x   5x 3x 3x   2x     5x           1x                                                                       8x         8x 8x     8x 2x         8x 8x 8x 8x 8x 2x           8x 8x 8x   8x 8x   8x           1x                                                                   5x 5x 5x 5x     5x 5x 2x 2x       2x     5x     5x     5x 5x 5x           1x                                           3x 3x 3x       3x 3x   3x 3x 3x   3x   3x   3x 3x   3x           1x                                         3x   3x 3x   3x       3x 3x 3x   3x   3x   3x   3x           1x                                 3x   3x   3x   3x 3x 3x   3x   3x           1x                                                     5x 5x       5x 5x 5x 5x 5x   5x 5x   5x   5x 5x 5x 5x         5x 5x 5x 5x   5x 5x 5x 5x     5x 5x   5x 5x 5x   5x           1x                             3x   3x 3x 3x   3x 3x   3x 3x   3x           1x                   3x 3x 3x   3x 3x   3x   3x                 1x                       3x       3x 3x 3x 3x   3x   3x 3x       3x 3x 3x   3x           1x                   3x       3x 3x 3x   3x 3x   3x 3x           1x                             5x       5x   5x 5x   5x   5x         5x   5x 5x 5x 5x 5x   5x 5x   5x 5x   5x    
 
 
import { TransactionBuilder, payments, address as bjsAddress, Transaction } from 'bitcoinjs-lib'
import * as BN from 'bn.js'
import {
  decodeB40, hash160, hash128, DUST_MINIMUM
} from './utils'
import { config } from '../config'
 
// support v1 and v2 price API endpoint return values
type AmountTypeV1 = number
type AmountTypeV2 = { units: string, amount: BN }
type AmountType = AmountTypeV1 | AmountTypeV2
 
// todo : add name length / character verification
 
/**
* @ignore
*/
export class BlockstackNamespace {
  namespaceID: string
 
  version: number
 
  lifetime: number
 
  coeff: number
 
  base: number
 
  buckets: Array<number>
 
  nonalphaDiscount: number
 
  noVowelDiscount: number
 
  constructor(namespaceID: string) {
    Iif (namespaceID.length > 19) {
      throw new Error('Namespace ID too long (19 chars max)')
    }
    Iif (!namespaceID.match('[0123456789abcdefghijklmnopqrstuvwxyz_-]+')) {
      throw new Error('Namespace ID can only use characters 0123456789abcdefghijklmnopqrstuvwxyz-_')
    }
 
    this.namespaceID = namespaceID
    this.version = -1
    this.lifetime = -1
    this.coeff = -1
    this.base = -1
    this.buckets = [-1]
    this.nonalphaDiscount = -1
    this.noVowelDiscount = -1
  }
 
  check() {
    try {
      this.setVersion(this.version)
      this.setLifetime(this.lifetime)
      this.setCoeff(this.coeff)
      this.setBase(this.base)
      this.setBuckets(this.buckets)
      this.setNonalphaDiscount(this.nonalphaDiscount)
      this.setNoVowelDiscount(this.noVowelDiscount)
      return true
    } catch (e) {
      return false
    }
  }
 
  setVersion(version: number) {
    Iif (version < 0 || version > 2 ** 16 - 1) {
      throw new Error('Invalid version: must be a 16-bit number')
    }
    this.version = version
  }
 
  setLifetime(lifetime: number) {
    Iif (lifetime < 0 || lifetime > 2 ** 32 - 1) {
      throw new Error('Invalid lifetime: must be a 32-bit number')
    }
    this.lifetime = lifetime
  }
 
  setCoeff(coeff: number) {
    Iif (coeff < 0 || coeff > 255) {
      throw new Error('Invalid coeff: must be an 8-bit number')
    }
    this.coeff = coeff
  }
 
  setBase(base: number) {
    Iif (base < 0 || base > 255) {
      throw new Error('Invalid base: must be an 8-bit number')
    }
    this.base = base
  }
 
  setBuckets(buckets: Array<number>) {
    Iif (buckets.length !== 16) {
      throw new Error('Invalid buckets: must have 16 entries')
    }
 
    for (let i = 0; i < buckets.length; i++) {
      Iif (buckets[i] < 0 || buckets[i] > 15) {
        throw new Error('Invalid buckets: must be 4-bit numbers')
      }
    }
 
    this.buckets = buckets.slice(0)
  }
 
  setNonalphaDiscount(nonalphaDiscount: number) {
    Iif (nonalphaDiscount <= 0 || nonalphaDiscount > 15) {
      throw new Error('Invalid nonalphaDiscount: must be a positive 4-bit number')
    }
    this.nonalphaDiscount = nonalphaDiscount
  }
 
  setNoVowelDiscount(noVowelDiscount: number) {
    Iif (noVowelDiscount <= 0 || noVowelDiscount > 15) {
      throw new Error('Invalid noVowelDiscount: must be a positive 4-bit number')
    }
    this.noVowelDiscount = noVowelDiscount
  }
 
  toHexPayload() {
    const lifeHex = `00000000${this.lifetime.toString(16)}`.slice(-8)
    const coeffHex = `00${this.coeff.toString(16)}`.slice(-2)
    const baseHex = `00${this.base.toString(16)}`.slice(-2)
    const bucketHex = this.buckets.map(b => b.toString(16)).reduce((b1, b2) => b1 + b2, '')
    const discountHex = this.nonalphaDiscount.toString(16) + this.noVowelDiscount.toString(16)
    const versionHex = `0000${this.version.toString(16)}`.slice(-4)
    const namespaceIDHex = Buffer.from(this.namespaceID).toString('hex')
 
    return lifeHex + coeffHex + baseHex + bucketHex + discountHex + versionHex + namespaceIDHex
  }
}
 
 
/**
* @ignore
*/
function asAmountV2(amount: AmountType): AmountTypeV2 {
  // convert an AmountType v1 or v2 to an AmountTypeV2.
  // the "units" of a v1 amount type are always 'BTC'
  Iif (typeof amount === 'number') {
    return { units: 'BTC', amount: new BN(String(amount)) }
  } else {
    return { units: amount.units, amount: amount.amount }
  }
}
 
/**
* @ignore
*/
function makeTXbuilder() {
  const txb = new TransactionBuilder(config.network.layer1)
  txb.setVersion(1)
  return txb
}
 
/**
* @ignore
*/
function opEncode(opcode: string): string {
  // NOTE: must *always* a 3-character string
  const res = `${config.network.MAGIC_BYTES}${opcode}`
  Iif (res.length !== 3) {
    throw new Error('Runtime error: invalid MAGIC_BYTES')
  }
  return res
}
 
/**
* @ignore
*/
export function makePreorderSkeleton(
  fullyQualifiedName: string, consensusHash: string, preorderAddress: string,
  burnAddress: string, burn: AmountType,
  registerAddress: string = null
): Transaction {
  // Returns a preorder tx skeleton.
  //   with 3 outputs : 1. the Blockstack Preorder OP_RETURN data
  //                    2. the Preorder's change address (5500 satoshi minimum)
  //                    3. the BURN
  //
  // 0     2  3                                     23             39          47            66
  // |-----|--|--------------------------------------|--------------|-----------|-------------|
  // magic op  hash160(fqn,scriptPubkey,registerAddr) consensus hash token burn  token type
  //                                                                 (optional)   (optional)
  //
  // output 0: name preorder code
  // output 1: preorder address
  // output 2: burn address
  //
  // Returns an unsigned serialized transaction.
  const burnAmount = asAmountV2(burn)
  const network = config.network
  const nameBuff = Buffer.from(decodeB40(fullyQualifiedName), 'hex') // base40
  const scriptPublicKey = bjsAddress.toOutputScript(preorderAddress, network.layer1)
 
  const dataBuffers = [nameBuff, scriptPublicKey]
 
  Eif (!!registerAddress) {
    const registerBuff = Buffer.from(registerAddress, 'ascii')
    dataBuffers.push(registerBuff)
  }
 
  const dataBuff = Buffer.concat(dataBuffers)
 
  const hashed = hash160(dataBuff)
 
  const opReturnBufferLen = burnAmount.units === 'BTC' ? 39 : 66
  const opReturnBuffer = Buffer.alloc(opReturnBufferLen)
  opReturnBuffer.write(opEncode('?'), 0, 3, 'ascii')
  hashed.copy(opReturnBuffer, 3)
  opReturnBuffer.write(consensusHash, 23, 16, 'hex')
 
  if (burnAmount.units !== 'BTC') {
    const burnHex = burnAmount.amount.toString(16, 2)
    Iif (burnHex.length > 16) {
      // exceeds 2**64; can't fit
      throw new Error(`Cannot preorder '${fullyQualifiedName}': cannot fit price into 8 bytes`)
    }
    const paddedBurnHex = `0000000000000000${burnHex}`.slice(-16)
 
    opReturnBuffer.write(paddedBurnHex, 39, 8, 'hex')
    opReturnBuffer.write(burnAmount.units, 47, burnAmount.units.length, 'ascii')
  }
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(preorderAddress, DUST_MINIMUM)
 
  if (burnAmount.units === 'BTC') {
    const btcBurnAmount = burnAmount.amount.toNumber()
    tx.addOutput(burnAddress, btcBurnAmount)
  } else {
    tx.addOutput(burnAddress, DUST_MINIMUM)
  }
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeRegisterSkeleton(
  fullyQualifiedName: string, ownerAddress: string,
  valueHash: string = null, burnTokenAmountHex: string = null
) {
  // Returns a register tx skeleton.
  //   with 2 outputs : 1. The register OP_RETURN
  //                    2. The owner address (can be different from REGISTER address on renewals)
 
  // You MUST make the first input a UTXO from the current OWNER *or* the
  //   funder of the PREORDER
 
  // in the case of a renewal, this would need to be modified to include a change address
  //  as output (3) before the burn output (4)
 
  /*
    Formats
 
    No zonefile hash, and pay with BTC:
 
    0    2  3                                  39
    |----|--|----------------------------------|
    magic op   name.ns_id (up to 37 bytes)
 
 
    With zonefile hash, and pay with BTC:
 
    0    2  3                                  39                  59
    |----|--|----------------------------------|-------------------|
    magic op   name.ns_id (37 bytes, 0-padded)     zone file hash
 
    output 0: name registration code
    output 1: owner address
  */
 
  let payload
 
  Iif (!!burnTokenAmountHex && !valueHash) {
    // empty value hash
    valueHash = '0000000000000000000000000000000000000000'
  }
 
  Eif (!!valueHash) {
    Iif (valueHash.length !== 40) {
      throw new Error('Value hash length incorrect. Expecting 20-bytes, hex-encoded')
    }
    if (!!burnTokenAmountHex) {
      Iif (burnTokenAmountHex.length !== 16) {
        throw new Error('Burn field length incorrect.  Expecting 8-bytes, hex-encoded')
      }
    }
 
    const payloadLen = burnTokenAmountHex ? 65 : 57
    payload = Buffer.alloc(payloadLen, 0)
    payload.write(fullyQualifiedName, 0, 37, 'ascii')
    payload.write(valueHash, 37, 20, 'hex')
    if (!!burnTokenAmountHex) {
      payload.write(burnTokenAmountHex, 57, 8, 'hex')
    }
  } else {
    payload = Buffer.from(fullyQualifiedName, 'ascii')
  }
 
  const opReturnBuffer = Buffer.concat([Buffer.from(opEncode(':'), 'ascii'), payload])
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(ownerAddress, DUST_MINIMUM)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeRenewalSkeleton(
  fullyQualifiedName: string, nextOwnerAddress: string, lastOwnerAddress: string,
  burnAddress: string, burn: AmountType, valueHash: string = null
) {
  /*
    Formats
 
    No zonefile hash, and pay with BTC:
 
    0    2  3                                  39
    |----|--|----------------------------------|
    magic op   name.ns_id (up to 37 bytes)
 
 
    With zonefile hash, and pay with BTC:
 
    0    2  3                                  39                  59
    |----|--|----------------------------------|-------------------|
    magic op   name.ns_id (37 bytes, 0-padded)     zone file hash
 
 
   With renewal payment in a token:
   (for register, tokens burned is not included)
   (for renew, tokens burned is the number of tokens to burn)
 
   0    2  3                                  39                  59                            67
   |----|--|----------------------------------|-------------------|------------------------------|
   magic op   name.ns_id (37 bytes, 0-padded)     zone file hash    tokens burned (big-endian)
 
   output 0: renewal code
   output 1: new owner address
   output 2: current owner address
   output 3: burn address
  */
  const burnAmount = asAmountV2(burn)
  const network = config.network
  const burnTokenAmount = burnAmount.units === 'BTC' ? null : burnAmount.amount
  const burnBTCAmount = burnAmount.units === 'BTC' 
    ? burnAmount.amount.toNumber() : DUST_MINIMUM
  
  let burnTokenHex = null
  if (!!burnTokenAmount) {
    const burnHex = burnTokenAmount.toString(16, 2)
    Iif (burnHex.length > 16) {
      // exceeds 2**64; can't fit 
      throw new Error(`Cannot renew '${fullyQualifiedName}': cannot fit price into 8 bytes`)
    }
    burnTokenHex = `0000000000000000${burnHex}`.slice(-16)
  }
 
  const registerTX = makeRegisterSkeleton(
    fullyQualifiedName, nextOwnerAddress, valueHash, burnTokenHex
  )
  const txB = TransactionBuilder.fromTransaction(
    registerTX, network.layer1
  )
  txB.addOutput(lastOwnerAddress, DUST_MINIMUM)
  txB.addOutput(burnAddress, burnBTCAmount)
  return txB.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeTransferSkeleton(
  fullyQualifiedName: string, consensusHash: string, newOwner: string,
  keepZonefile: boolean = false
): Transaction {
  // Returns a transfer tx skeleton.
  //   with 2 outputs : 1. the Blockstack Transfer OP_RETURN data
  //                    2. the new owner with a DUST_MINIMUM value (5500 satoshi)
  //
  // You MUST make the first input a UTXO from the current OWNER
  //
  // Returns an unsigned serialized transaction.
  /*
    Format
 
    0     2  3    4                   20              36
    |-----|--|----|-------------------|---------------|
    magic op keep  hash128(name.ns_id) consensus hash
             data?
 
    output 0: transfer code
    output 1: new owner
  */
  const opRet = Buffer.alloc(36)
  let keepChar = '~'
  Iif (keepZonefile) {
    keepChar = '>'
  }
 
  opRet.write(opEncode('>'), 0, 3, 'ascii')
  opRet.write(keepChar, 3, 1, 'ascii')
 
  const hashed = hash128(Buffer.from(fullyQualifiedName, 'ascii'))
  hashed.copy(opRet, 4)
  opRet.write(consensusHash, 20, 16, 'hex')
 
  const opRetPayload = payments.embed({ data: [opRet] }).output
 
  const tx = makeTXbuilder()
 
  tx.addOutput(opRetPayload, 0)
  tx.addOutput(newOwner, DUST_MINIMUM)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeUpdateSkeleton(
  fullyQualifiedName: string, consensusHash: string, valueHash: string
): Transaction {
  // Returns an update tx skeleton.
  //   with 1 output : 1. the Blockstack update OP_RETURN
  //
  // You MUST make the first input a UTXO from the current OWNER
  //
  // Returns an unsigned serialized transaction.
  //
  // output 0: the revoke code
  /*
    Format:
 
    0     2  3                                   19                      39
    |-----|--|-----------------------------------|-----------------------|
    magic op  hash128(name.ns_id,consensus hash) hash160(data)
 
    output 0: update code
  */
 
  const opRet = Buffer.alloc(39)
 
  const nameBuff = Buffer.from(fullyQualifiedName, 'ascii')
  const consensusBuff = Buffer.from(consensusHash, 'ascii')
 
  const hashedName = hash128(Buffer.concat(
    [nameBuff, consensusBuff]
  ))
 
  opRet.write(opEncode('+'), 0, 3, 'ascii')
  hashedName.copy(opRet, 3)
  opRet.write(valueHash, 19, 20, 'hex')
 
  const opRetPayload = payments.embed({ data: [opRet] }).output
 
  const tx = makeTXbuilder()
 
  tx.addOutput(opRetPayload, 0)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeRevokeSkeleton(fullyQualifiedName: string) {
  // Returns a revoke tx skeleton
  //    with 1 output: 1. the Blockstack revoke OP_RETURN
  //
  // You MUST make the first input a UTXO from the current OWNER
  //
  // Returns an unsigned serialized transaction
  /*
   Format:
 
   0    2  3                             39
   |----|--|-----------------------------|
   magic op   name.ns_id (37 bytes)
 
   output 0: the revoke code
  */
 
  const opRet = Buffer.alloc(3)
 
  const nameBuff = Buffer.from(fullyQualifiedName, 'ascii')
 
  opRet.write(opEncode('~'), 0, 3, 'ascii')
 
  const opReturnBuffer = Buffer.concat([opRet, nameBuff])
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeNamespacePreorderSkeleton(
  namespaceID: string, consensusHash: string, preorderAddress: string,
  registerAddress: string, burn: AmountType
): Transaction {
  // Returns a namespace preorder tx skeleton.
  // Returns an unsigned serialized transaction.
  /*
   Formats:
 
   Without STACKS:
 
   0     2   3                                      23               39
   |-----|---|--------------------------------------|----------------|
   magic op  hash(ns_id,script_pubkey,reveal_addr)   consensus hash
 
 
   with STACKs:
 
   0     2   3                                      23               39                         47
   |-----|---|--------------------------------------|----------------|--------------------------|
   magic op  hash(ns_id,script_pubkey,reveal_addr)   consensus hash    token fee (big-endian)
 
   output 0: namespace preorder code
   output 1: change address
   otuput 2: burn address
  */
 
  const burnAmount = asAmountV2(burn)
  Iif (burnAmount.units !== 'BTC' && burnAmount.units !== 'STACKS') {
    throw new Error(`Invalid burnUnits ${burnAmount.units}`)
  }
 
  const network = config.network
  const burnAddress = network.getDefaultBurnAddress()
  const namespaceIDBuff = Buffer.from(decodeB40(namespaceID), 'hex') // base40
  const scriptPublicKey = bjsAddress.toOutputScript(preorderAddress, network.layer1)
  const registerBuff = Buffer.from(registerAddress, 'ascii')
 
  const dataBuffers = [namespaceIDBuff, scriptPublicKey, registerBuff]
  const dataBuff = Buffer.concat(dataBuffers)
 
  const hashed = hash160(dataBuff)
  
  let btcBurnAmount = DUST_MINIMUM
  let opReturnBufferLen = 39
  Eif (burnAmount.units === 'STACKS') {
    opReturnBufferLen = 47
  } else {
    btcBurnAmount = burnAmount.amount.toNumber()
  }
 
  const opReturnBuffer = Buffer.alloc(opReturnBufferLen)
  opReturnBuffer.write(opEncode('*'), 0, 3, 'ascii')
  hashed.copy(opReturnBuffer, 3)
  opReturnBuffer.write(consensusHash, 23, 16, 'hex')
 
  Eif (burnAmount.units === 'STACKS') {
    const burnHex = burnAmount.amount.toString(16, 2)
    const paddedBurnHex = `0000000000000000${burnHex}`.slice(-16)
    opReturnBuffer.write(paddedBurnHex, 39, 8, 'hex')
  }
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(preorderAddress, DUST_MINIMUM)
  tx.addOutput(burnAddress, btcBurnAmount)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeNamespaceRevealSkeleton(
  namespace: BlockstackNamespace, revealAddress: string
) {
  /*
   Format:
 
   0     2   3    7     8     9    10   11   12   13   14    15    16    17       18      20     39
   |-----|---|----|-----|-----|----|----|----|----|----|-----|-----|-----|--------|-------|-------|
   magic  op  life coeff. base 1-2  3-4  5-6  7-8  9-10 11-12 13-14 15-16 nonalpha version  ns ID
                                                  bucket exponents        no-vowel
                                                                          discounts
   
   output 0: namespace reveal code
   output 1: reveal address
  */
  const hexPayload = namespace.toHexPayload()
 
  const opReturnBuffer = Buffer.alloc(3 + hexPayload.length / 2)
  opReturnBuffer.write(opEncode('&'), 0, 3, 'ascii')
  opReturnBuffer.write(hexPayload, 3, hexPayload.length / 2, 'hex')
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(revealAddress, DUST_MINIMUM)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeNamespaceReadySkeleton(namespaceID: string) {
  /*
   Format:
 
   0     2  3  4           23
   |-----|--|--|------------|
   magic op  .  ns_id
 
   output 0: namespace ready code
   */
  const opReturnBuffer = Buffer.alloc(3 + namespaceID.length + 1)
  opReturnBuffer.write(opEncode('!'), 0, 3, 'ascii')
  opReturnBuffer.write(`.${namespaceID}`, 3, namespaceID.length + 1, 'ascii')
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
 
  return tx.buildIncomplete()
}
 
 
// type bitcoin.payments.p2data bitcoin.payments.embed
 
/**
* @ignore
*/
export function makeNameImportSkeleton(name: string, recipientAddr: string, zonefileHash: string) {
  /*
   Format:
 
    0    2  3                             39
    |----|--|-----------------------------|
    magic op   name.ns_id (37 bytes)
 
   Output 0: the OP_RETURN
   Output 1: the recipient
   Output 2: the zonefile hash
 */
  Iif (zonefileHash.length !== 40) {
    throw new Error('Invalid zonefile hash: must be 20 bytes hex-encoded')
  }
 
  const network = config.network
  const opReturnBuffer = Buffer.alloc(3 + name.length)
  opReturnBuffer.write(opEncode(';'), 0, 3, 'ascii')
  opReturnBuffer.write(name, 3, name.length, 'ascii')
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
 
  const tx = makeTXbuilder()
  const zonefileHashB58 = bjsAddress.toBase58Check(
    Buffer.from(zonefileHash, 'hex'), network.layer1.pubKeyHash
  )
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(recipientAddr, DUST_MINIMUM)
  tx.addOutput(zonefileHashB58, DUST_MINIMUM)
 
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeAnnounceSkeleton(messageHash: string) {
  /*
    Format:
 
    0    2  3                             23
    |----|--|-----------------------------|
    magic op   message hash (160-bit)
 
    output 0: the OP_RETURN
  */
  Iif (messageHash.length !== 40) {
    throw new Error('Invalid message hash: must be 20 bytes hex-encoded')
  }
 
  const opReturnBuffer = Buffer.alloc(3 + messageHash.length / 2)
  opReturnBuffer.write(opEncode('#'), 0, 3, 'ascii')
  opReturnBuffer.write(messageHash, 3, messageHash.length / 2, 'hex')
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  return tx.buildIncomplete()
}
 
/**
* @ignore
*/
export function makeTokenTransferSkeleton(recipientAddress: string, consensusHash: string,
                                          tokenType: string, tokenAmount: BN,
                                          scratchArea: string
) {
  /*
   Format:
 
    0     2  3              19         38          46                        80
    |-----|--|--------------|----------|-----------|-------------------------|
    magic op  consensus_hash token_type amount (BE) scratch area
                             (ns_id)
 
    output 0: token transfer code
    output 1: recipient address
  */
  Iif (scratchArea.length > 34) {
    throw new Error('Invalid scratch area: must be no more than 34 bytes')
  }
 
  const opReturnBuffer = Buffer.alloc(46 + scratchArea.length)
 
  const tokenTypeHex = Buffer.from(tokenType).toString('hex')
  const tokenTypeHexPadded = `00000000000000000000000000000000000000${tokenTypeHex}`.slice(-38)
 
  const tokenValueHex = tokenAmount.toString(16, 2)
 
  Iif (tokenValueHex.length > 16) {
    // exceeds 2**64; can't fit
    throw new Error(`Cannot send tokens: cannot fit ${tokenAmount.toString()} into 8 bytes`)
  }
 
  const tokenValueHexPadded = `0000000000000000${tokenValueHex}`.slice(-16)
 
  opReturnBuffer.write(opEncode('$'), 0, 3, 'ascii')
  opReturnBuffer.write(consensusHash, 3, consensusHash.length / 2, 'hex')
  opReturnBuffer.write(tokenTypeHexPadded, 19, tokenTypeHexPadded.length / 2, 'hex')
  opReturnBuffer.write(tokenValueHexPadded, 38, tokenValueHexPadded.length / 2, 'hex')
  opReturnBuffer.write(scratchArea, 46, scratchArea.length, 'ascii')
 
  const nullOutput = payments.embed({ data: [opReturnBuffer] }).output
  const tx = makeTXbuilder()
 
  tx.addOutput(nullOutput, 0)
  tx.addOutput(recipientAddress, DUST_MINIMUM)
 
  return tx.buildIncomplete()
}