# All files / src wallet.ts

80.41% Statements 78/97
41.67% Branches 10/24
78.57% Functions 22/28
80.85% Lines 76/94

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
    3801x
    1x
    1x
    1x
    1x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    1x

    2x
    2x
    2x
    128x
    128x
    128x

    2x

    14x

    20x

    1x

    2x
    2x
    2x
    2x
    2x
    2x

    1x

    2x

    1x

    1x

    22x

    4x

    2x

    10x
    10x

    10x

    10x

    10x
    10x
    10x
    10x

    2x

    2x

    2x

    2x
    2x

    2x

    2x

    2x
    2x

    12x

    2x
    2x
    2x
    2x

    2x

    2x

    22x

    2x
    2x
    22x

    22x

    2x

    10x

    10x
    10x
    10x
    8x

    10x
    10x
    10x
    10x

    10x

     import { payments, bip32, BIP32Interface } from 'bitcoinjs-lib'
    import { mnemonicToSeed, generateMnemonic } from 'bip39'
    import { encryptMnemonic, decryptMnemonic } from './encryption/wallet'
    import { randomBytes, GetRandomBytes } from './encryption/cryptoRandom'
    import { createSha2Hash } from './encryption/sha2Hash'
    import { TriplesecDecryptSignature } from './encryption/cryptoUtils'

    const APPS_NODE_INDEX = 0
    const IDENTITY_KEYCHAIN = 888
    const BLOCKSTACK_ON_BITCOIN = 0

    const BITCOIN_BIP_44_PURPOSE = 44
    const BITCOIN_COIN_TYPE = 0
    const BITCOIN_ACCOUNT_INDEX = 0

    const EXTERNAL_ADDRESS = 'EXTERNAL_ADDRESS'
    const CHANGE_ADDRESS = 'CHANGE_ADDRESS'

    /**
     *
     * @ignore
     */
    export type IdentityKeyPair = {
      key: string,
      keyID: string,
      address: string,
      appsNodeKey: string,
      salt: string
    }

    /**
     *
     * @ignore
     */
    function hashCode(string: string) {
      let hash = 0
      Iif (string.length === 0) return hash
      for (let i = 0; i < string.length; i++) {
        const character = string.charCodeAt(i)
        hash = (hash << 5) - hash + character
        hash &= hash
      }
      return hash & 0x7fffffff
    }

    /**
     *
     * @ignore
     */
    function getNodePrivateKey(node: BIP32Interface): string {
      return `${node.privateKey.toString('hex')}01`
    }

    /**
     *
     * @ignore
     */
    function getNodePublicKey(node: BIP32Interface): string {
      return node.publicKey.toString('hex')
    }

    /**
     * Get a BIP32 node for an application-specific domain.
     * @param {String} appsNode - the BIP32Interface ir base58-encoded private key for
     * applications node
     * @param {String} salt - a string, used to salt the
     * application-specific addresses
     * @param {String} appDomain - the appDomain to generate a key for
     * @return {String} the private key hex-string. this will be a 64
     * character string
     * @ignore
     */
    export async function getLegacyAppNode(
      appsNode: string | BIP32Interface,
      salt: string, appDomain: string): Promise<BIP32Interface> {
      const sha2Hash = await createSha2Hash()
      const hashBuffer = await sha2Hash.digest(Buffer.from(`${appDomain}${salt}`))
      const hash = hashBuffer.toString('hex')
      const appIndex = hashCode(hash)
      const appNodeInstance = typeof appsNode === 'string' ? bip32.fromBase58(appsNode) : appsNode
      return appNodeInstance.deriveHardened(appIndex)
    }

    /**
     * The `BlockstackWallet` class manages the hierarchical derivation
     * paths for a standard Blockstack client wallet. This includes paths
     * for Bitcoin payment address, Blockstack identity addresses, Blockstack
     * application specific addresses.
     *
     * @ignore
     */
    export class BlockstackWallet {
      rootNode: BIP32Interface

      constructor(rootNode: BIP32Interface) {
        this.rootNode = rootNode
      }

      toBase58(): string {
        return this.rootNode.toBase58()
      }

      /**
       * Initialize a Blockstack wallet from a seed buffer
       * @param {Buffer} seed - the input seed for initializing the root node
       *  of the hierarchical wallet
       * @return {BlockstackWallet} the constructed wallet
       */
      static fromSeedBuffer(seed: Buffer): BlockstackWallet {
        return new BlockstackWallet(bip32.fromSeed(seed))
      }

      /**
       * Initialize a Blockstack wallet from a base58 string
       * @param {string} keychain - the Base58 string used to initialize
       *  the root node of the hierarchical wallet
       * @return {BlockstackWallet} the constructed wallet
       */
      static fromBase58(keychain: string): BlockstackWallet {
        return new BlockstackWallet(bip32.fromBase58(keychain))
      }

      /**
       * Initialize a blockstack wallet from an encrypted phrase & password. Throws
       * if the password is incorrect. Supports all formats of Blockstack phrases.
       * @param {string} data - The encrypted phrase as a hex-encoded string
       * @param {string} password - The plain password
       * @return {Promise<BlockstackWallet>} the constructed wallet
       *
       * @ignore
       */
      static async fromEncryptedMnemonic(
        data: string | Buffer,
        password: string,
        triplesecDecrypt: TriplesecDecryptSignature): Promise<BlockstackWallet> {
        try {
          const mnemonic = await decryptMnemonic(data, password, triplesecDecrypt)
          const seed = await mnemonicToSeed(mnemonic)
          return new BlockstackWallet(bip32.fromSeed(seed))
        } catch (err) {
          if (err.message && err.message.startsWith('bad header;')) {
            throw new Error('Incorrect password')
          } else {
            throw err
          }
        }
      }

      /**
       * Generate a BIP-39 12 word mnemonic
       * @return {Promise<string>} space-separated 12 word phrase
       */
      static generateMnemonic() {
        return generateMnemonic(128, randomBytes)
      }

      /**
       * Encrypt a mnemonic phrase with a password
       * @param {string} mnemonic - Raw mnemonic phrase
       * @param {string} password - Password to encrypt mnemonic with
       * @return {Promise<string>} Hex-encoded encrypted mnemonic
       *
       */
      static async encryptMnemonic(mnemonic: string, password: string, opts?: {
        getRandomBytes?: GetRandomBytes
      }) {
        const encryptedBuffer = await encryptMnemonic(mnemonic, password, opts)
        return encryptedBuffer.toString('hex')
      }

      getIdentityPrivateKeychain(): BIP32Interface {
        return this.rootNode
          .deriveHardened(IDENTITY_KEYCHAIN)
          .deriveHardened(BLOCKSTACK_ON_BITCOIN)
      }

      getBitcoinPrivateKeychain(): BIP32Interface {
        return this.rootNode
          .deriveHardened(BITCOIN_BIP_44_PURPOSE)
          .deriveHardened(BITCOIN_COIN_TYPE)
          .deriveHardened(BITCOIN_ACCOUNT_INDEX)
      }

      getBitcoinNode(addressIndex: number, chainType: string = EXTERNAL_ADDRESS): BIP32Interface {
        return BlockstackWallet.getNodeFromBitcoinKeychain(
          this.getBitcoinPrivateKeychain().toBase58(),
          addressIndex,
          chainType
        )
      }

      getIdentityAddressNode(identityIndex: number): BIP32Interface {
        const identityPrivateKeychain = this.getIdentityPrivateKeychain()
        return identityPrivateKeychain.deriveHardened(identityIndex)
      }

      static getAppsNode(identityNode: BIP32Interface): BIP32Interface {
        return identityNode.deriveHardened(APPS_NODE_INDEX)
      }

      /**
       * Get a salt for use with creating application specific addresses
       * @return {String} the salt
       */
      async getIdentitySalt(): Promise<string> {
        const identityPrivateKeychain = this.getIdentityPrivateKeychain()
        // TODO: this is being decoded as a utf8 string rather than a hex string?
        const publicKeyHex = Buffer.from(getNodePublicKey(identityPrivateKeychain))
        const sha2Hash = await createSha2Hash()
        const hash = await sha2Hash.digest(publicKeyHex)
        return hash.toString('hex')
      }

      /**
       * Get a bitcoin receive address at a given index
       * @param {number} addressIndex - the index of the address
       * @return {String} address
       */
      getBitcoinAddress(addressIndex: number): string {
        return BlockstackWallet.getAddressFromBIP32Node(this.getBitcoinNode(addressIndex))
      }

      /**
       * Get the private key hex-string for a given bitcoin receive address
       * @param {number} addressIndex - the index of the address
       * @return {String} the hex-string. this will be either 64
       * characters long to denote an uncompressed bitcoin address, or 66
       * characters long for a compressed bitcoin address.
       */
      getBitcoinPrivateKey(addressIndex: number): string {
        return getNodePrivateKey(this.getBitcoinNode(addressIndex))
      }

      /**
       * Get the root node for the bitcoin public keychain
       * @return {String} base58-encoding of the public node
       */
      getBitcoinPublicKeychain(): BIP32Interface {
        return this.getBitcoinPrivateKeychain().neutered()
      }

      /**
       * Get the root node for the identity public keychain
       * @return {String} base58-encoding of the public node
       */
      getIdentityPublicKeychain(): BIP32Interface {
        return this.getIdentityPrivateKeychain().neutered()
      }

      static getNodeFromBitcoinKeychain(
        keychainBase58: string,
        addressIndex: number,
        chainType: string = EXTERNAL_ADDRESS
      ): BIP32Interface {
        let chain
        Eif (chainType === EXTERNAL_ADDRESS) {
          chain = 0
        } else if (chainType === CHANGE_ADDRESS) {
          chain = 1
        } else {
          throw new Error('Invalid chain type')
        }
        const keychain = bip32.fromBase58(keychainBase58)

        return keychain.derive(chain).derive(addressIndex)
      }

      /**
       * Get a bitcoin address given a base-58 encoded bitcoin node
       * (usually called the account node)
       * @param {String} keychainBase58 - base58-encoding of the node
       * @param {number} addressIndex - index of the address to get
       * @param {String} chainType - either 'EXTERNAL_ADDRESS' (for a
       * "receive" address) or 'CHANGE_ADDRESS'
       * @return {String} the address
       */
      static getAddressFromBitcoinKeychain(keychainBase58: string, addressIndex: number,
                                           chainType: string = EXTERNAL_ADDRESS): string {
        return BlockstackWallet.getAddressFromBIP32Node(BlockstackWallet
          .getNodeFromBitcoinKeychain(keychainBase58, addressIndex, chainType))
      }

      /**
       * Get a ECDSA private key hex-string for an application-specific
       *  address.
       * @param {String} appsNodeKey - the base58-encoded private key for
       * applications node (the `appsNodeKey` return in getIdentityKeyPair())
       * @param {String} salt - a string, used to salt the
       * application-specific addresses
       * @param {String} appDomain - the appDomain to generate a key for
       * @return {String} the private key hex-string. this will be a 64
       * character string
       */
      static async getLegacyAppPrivateKey(
        appsNodeKey: string,
        salt: string, appDomain: string): Promise<string> {
        const appNode = await getLegacyAppNode(appsNodeKey, salt, appDomain)
        return getNodePrivateKey(appNode).slice(0, 64)
      }

      static getAddressFromBIP32Node(node: BIP32Interface) {
        return payments.p2pkh({ pubkey: node.publicKey }).address
      }

      /**
       * Get a ECDSA private key hex-string for an application-specific
       *  address.
       * @param {String} appsNodeKey - the base58-encoded private key for
       * applications node (the `appsNodeKey` return in getIdentityKeyPair())
       * @param {String} salt - a string, used to salt the
       * application-specific addresses
       * @param {String} appDomain - the appDomain to generate a key for
       * @return {String} the private key hex-string. this will be a 64
       * character string
       */
      static async getAppPrivateKey(appsNodeKey: string, salt: string, appDomain: string):
        Promise<string> {
        const sha2Hash = await createSha2Hash()
        const hashBuffer = await sha2Hash.digest(Buffer.from(`${appDomain}${salt}`))
        const hash = hashBuffer.toString('hex')
        const appIndexHexes: string[] = []
        // note: there's hardcoded numbers here, precisely because I want this
        //   code to be very specific to the derivation paths we expect.
        Iif (hash.length !== 64) {
          throw new Error(`Unexpected app-domain hash length of ${hash.length}`)
        }
        for (let i = 0; i < 11; i++) { // split the hash into 3-byte chunks
          // because child nodes can only be up to 2^31,
          // and we shouldn't deal in partial bytes.
          appIndexHexes.push(hash.slice(i * 6, i * 6 + 6))
        }
        let appNode = bip32.fromBase58(appsNodeKey)
        appIndexHexes.forEach((hex) => {
          Iif (hex.length > 6) {
            throw new Error('Invalid hex string length')
          }
          appNode = appNode.deriveHardened(parseInt(hex, 16))
        })
        return getNodePrivateKey(appNode).slice(0, 64)
      }

      /**
       * Get the keypair information for a given identity index. This
       * information is used to obtain the private key for an identity address
       * and derive application specific keys for that address.
       * @param {number} addressIndex - the identity index
       * @param {boolean} alwaysUncompressed - if true, always return a
       *   private-key hex string corresponding to the uncompressed address
       * @return {Object} an IdentityKeyPair type object with keys:
       *   .key {String} - the private key hex-string
       *   .keyID {String} - the public key hex-string
       *   .address {String} - the identity address
       *   .appsNodeKey {String} - the base-58 encoding of the applications node
       *   .salt {String} - the salt used for creating app-specific addresses
       */
      async getIdentityKeyPair(
        addressIndex: number,
        alwaysUncompressed: boolean = false): Promise<IdentityKeyPair> {
        const identityNode = this.getIdentityAddressNode(addressIndex)

        const address = BlockstackWallet.getAddressFromBIP32Node(identityNode)
        let identityKey = getNodePrivateKey(identityNode)
        if (alwaysUncompressed && identityKey.length === 66) {
          identityKey = identityKey.slice(0, 64)
        }

        const identityKeyID = getNodePublicKey(identityNode)
        const appsNodeKey = BlockstackWallet.getAppsNode(identityNode).toBase58()
        const salt = await this.getIdentitySalt()
        const keyPair = {
          key: identityKey,
          keyID: identityKeyID,
          address,
          appsNodeKey,
          salt
        }
        return keyPair
      }
    }