bitcoinjs / bitcoinjs-lib

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

Issue with mainnet WIF and testnet transaction #972

Closed musafarouk closed 6 years ago

musafarouk commented 6 years ago

https://github.com/bitcoinjs/bitcoinjs-lib/blob/f4caaf42e7b58332d74c1540f88bcda7e55b82e6/test/integration/transactions.js#L14

I'm trying to do a 1-to-1 testnet transaction but using a testnet address. I keep getting an invalid network version error. How do I solve this?

musafarouk commented 6 years ago
sendBTC (paperWallet, toAddress, amount, txID) {
    const keyPair = bitcoin.ECPair.fromWIF(paperWallet.privateKey, bitcoin.networks.testnet)
    const txb = new bitcoin.TransactionBuilder()
      txb.addInput(txID , 0) // previous transactionId from the address at index 0
      txb.addOutput(toAddress, amount) 
      txb.sign(0, keyPair)
      txb.build().toHex()
      console.log('transfer successful')

That is the code I used

edit by dcousens: I fixed a txb.sign typo you had

dabura667 commented 6 years ago

paper wallet keys already have network information embedded in them.

Your private key probably starts with K or L or 5 but Testnet private keys do not start with those letters.

So bitcoinjs-lib reads your WIF and it says Bitcoin Mainnet... but then it reads your testnet network you passed it and says "these don't match"

You need to generate a testnet private key:

console.log(bitcoin.ECPair.makeRandom({network:bitcoin.networks.testnet}).toWIF())

musafarouk commented 6 years ago

screen_shot_2017-12-31_at_8 08 51_pm

dabura667 commented 6 years ago
  1. you are probably doing bitcoin.ECPair.fromWIF(...).toString() which will give you a string '[object Object]' and you are trying to look up the balance of '[object Object]'... you want to use bitcoin.ECPair.fromWIF(...).getAddress() to get the string of the address.
  2. You are passing bitcoin.networks.testnet to fromWIF... which means it is expecting a testnet key. But you are not passing it a testnet key, so it breaks.

Mainnet (real bitcoin) WIF keys: start with 5, K, L 5KdtksGvv5138dWaEVnwkKQXpV316YDgt8Dz8hR4hPgcFEPAE3d L1ftFE9RPmWtrLBK2FiGteCEt1BuJoQ98nTzn9ZuVoTZVVjsfrgj KyovDBFmtF4bs2B8ZD7BBGKKbU4Vswu8FPE6dM5b9bZdYV8unaqp

Testnet WIF keys: start with c or 9 cU5YmqypsqeMokL3faxKLsW5uMEwpfmYq8bRQjWhAHS718o3XRX2 92b8kq9n7MbN99Eq7d6z4nwW678YtsURRcJd26KjUQRHR6VgAd3

You are entering a key with 5 K or L, but you are telling bitcoinjs-lib "THIS KEY MUST BE bitcoin.networks.testnet OR ELSE THROW A BIG ERROR!!!!"

Possible solutions:

  1. change to bitcoin.networks.bitcoin
  2. don't pass the network at all: bitcoin.ECPair.fromWIF(paperWallet.privateKey)