bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.69k stars 2.11k forks source link

Creating testnet WIF creates a mainnet WIF #1642

Closed ghost closed 4 years ago

ghost commented 4 years ago
const bitcoin = require('bitcoinjs-lib')
const bip39 = require('bip39')
const bip32 = require('bip32')
const crypto = require('crypto')
const network = bitcoin.networks.testnet

const randomBytes = crypto.randomBytes(16)
const hexBytes = randomBytes.toString('hex')
const mnemonic = bip39.entropyToMnemonic(hexBytes)
const seed = bip39.mnemonicToSeedSync(mnemonic)
const root = bip32.fromSeed(seed)

const bip44CoinScheme = "m/44'/1'/0'" 
const basePath = '/0/0' // first account in derivation path

// m/44'/1'/0'/0/0
const bip44BasePath = bip44CoinScheme + basePath
const bip44Child0 = root.derivePath(bip44BasePath)

const bip44Address = bitcoin.payments.p2pkh({ pubkey: bip44Child0.publicKey, network: network }).address

const bip44child0Wif = bip44Child0.toWIF({network: network})

Running that code yields:

hexbytes = 501a9147648eaa36d2d16aba2e97e8ca
bip44Address = mjTfrkLmGgT7nVPyFScG4ACgJNCb5DWPXj
bip44child0Wif = KxvR2TawBKvJ6xXtUgRD4psj31qtm24wELNQS4WAEpnp4r5WV2RB

The WIF appears to be in mainnet format so when I attempt to sign a transaction I get the error Error: Invalid network version

junderw commented 4 years ago

toWIF just uses the network of the bip32 object.

pass the network to the fromSeed method.