bitcoinjs-lib: Newbie here, need some help, stuck on psbt transaction creation and signing

Didn’t have problem with the output, but when processing input, kept showing “Error: Data for input key witness Utxo is incorrect: Expected {script: Buffer; Value: number}” and got …". The problem is, I already got the appropriate format there.

Also, when signing, though with the proper private key, it kept popping “No transactions were signed” errors.

the input is a 2 of 3 multisig input

Please help, thanks

Here’s my code for transaction creation

var p = 'https://api.smartbit.com.au/v1/blockchain/address/'+addr;
const resp = await fetch(p);
const r = await resp.json();
var tx = new bitcoin.Psbt({
  network: bitcoin.networks.bitcoin
});
var amount = r.address.confirmed.balance_int;
for(var j = 0; j < r.address.transactions.length; j++) {
  var scriptpubkey='';
  for (var k = 0; k < r.address.transactions[j].output_count; k++) {
    if (r.address.transactions[j].outputs[k].addresses[0]==addr) {
      scriptpubkey=r.address.transactions[j].outputs[k].script_pub_key.hex;
    }
  }
  await tx.addInput({
    hash: r.address.transactions[j].hash,
    index: j,
    witnessUtxo: {
      script: Buffer.from(scriptpubkey, 'hex'),
      value: r.address.transactions[j].output_amount_int,
    },
  });
  var tx_receiver=await txr.toHex();
}

Here’s the code for signing

sign = function (message, key) {
  var psbt = bitcoin.Psbt.fromHex(message);
  var keyPair = bitcoin.ECPair.fromWIF(key);
  psbt.signAllInputs(keyPair);
  return psbt.toHex();
}

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 30 (14 by maintainers)

Most upvoted comments

Additionally, I believe the way you assign vout on your inputs (incrementing on the loop) needs to be corrected.

The vout field on the input should be the UTXO’s index on the previous transaction you are spending from. I think, in your case, you want to use tx_output_n from the API response.

I did a workshop on building a wallet with BitcoinJS that you might find helpful for explaining how to construct a transaction. Specifically you want to look at Part 3.

Repo: https://github.com/KayBeSee/tabconf-workshop Video: https://www.youtube.com/watch?v=Bwz2P2hPVpk

  1. Clean up your code before asking questions, please.
  2. You are very confused by the data given by the API. The index you pass to addInput should be the output index, not the index of the transaction in the list from the API. Also, transaction output amount is just an estimate from the API, you want to get the specific amount of the output you’re using.

Using their unspent API will be easier for you to understand I think:

'https://api.smartbit.com.au/v1/blockchain/address/' + addr + '/unspent';