invalid prefix with bitcoinjs-lib

771 Views Asked by At

I have this code:

var bitcoin = require('bitcoinjs-lib')

var testnet=bitcoin.networks.testnet;
var bitcoin = require('bitcoinjs-lib')
var privateKey = 'cV1hT8dqY6T3UnFjKk883N3nr895JeBVFjMMqi6VbPgDZyfVfzAF'
var keyPair = bitcoin.ECPair.fromWIF(privateKey, testnet);
const RawTransaction = new bitcoin.Psbt(testnet)
RawTransaction.addInput({hash:'9412f5e46f63a65ae140d36cbe6fe137e7f6b047759a8487a73abd5f25727bff', index:0})
RawTransaction.addOutput({address:'tb1q8selj8yz0yh79esajd77x3r6ea5q0vf8svjev4', value:0.00001})


RawTransaction.sign(0, keyPair)
    
var Transaction = RawTransaction.build().toHex();
console.log(Transaction)

I have this error:

Error: tb1q8selj8yz0yh79esajd77x3r6ea5q0vf8svjev4 has an invalid prefix

I dont understand what happen. The destination address is generated by electrum wallet and seems to be correct. Im using testnet.

2

There are 2 best solutions below

0
On

Here is the code that checks the address:

if (decodeBech32.prefix !== network.bech32)
    throw new Error(address + ' has an invalid prefix');

By default the library uses mainnet network and the check fails due to testnet address prefix.

Try this:

const RawTransaction = new bitcoin.Psbt({ network: testnet })
0
On

The correct syntax now (2023) is:

const RawTransaction = new bitcoin.Psbt({ network: bitcoin.networks.testnet })