bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error validating transaction: Script was NOT verified successfully

21fahm opened this issue · comments

 const keypair = ECPair.fromPrivateKey(
    Buffer.from(
      "951387c5998765d48ec84ef6a7a2ed694543988cd433b41aef1179da38c28d03",
      "hex"
    )
  );
  const output_script = bitcoin.payments.p2wpkh({
    // pubkey: keypair.publicKey,
    pubkey: keypair.publicKey,
    network: bitcoin.networks.testnet,
  });

  const utxosData = {
    address: "tb1ql8um76uveq0uzjhl4gvk2sz39ree3ucsehk5w8",
    total_received: 73359,
    total_sent: 0,
    balance: 73359,
    unconfirmed_balance: 0,
    final_balance: 73359,
    n_tx: 1,
    unconfirmed_n_tx: 0,
    final_n_tx: 1,
    txrefs: [
      {
        tx_hash:
          "6bb054684263c21cf4bf9167a3c8443ec3c278b37b3387c052596dd511c7ad71",
        block_height: 2585447,
        tx_input_n: -1,
        tx_output_n: 1,
        value: 73359,
        ref_balance: 73359,
        spent: false,
        confirmations: 4,
        confirmed: "2024-04-06T19:35:59Z",
        double_spend: false,
      },
    ],
    tx_url: "https://api.blockcypher.com/v1/btc/test3/txs/",
  };

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

  txb.addInput({
    hash: utxosData.txrefs[0].tx_hash,
    index: utxosData.txrefs[0].tx_output_n,
    witnessUtxo: {
      script: output_script.output,
      value: utxosData.txrefs[0].value,
    },
  });

  // Destination address and amount to send (in satoshis)
  const targetAddress = "tb1qdtg5tkaz8ucysfcy8kerustg53kflykd95t7x5"; // Replace with destination address
  const amountToSend = 10000; // Replace with amount in satoshis

  // Add output
  txb.addOutput({
    address: targetAddress,
    value: amountToSend,
  });

  txb.signInput(0, keypair);

  txb.finalizeAllInputs();

  const balance = utxosData.txrefs[0].value - amountToSend;
  const change = balance - txb.getFeeRate();

  // Add output
  txb.addOutput({
    address: output_script.address,
    value: change,
  });

  const final = txb.extractTransaction();

  const txHex = final.toHex();

  //  Broadcast the transaction
  const broadcastResponse = await fetch(
    "https://api.blockcypher.com/v1/btc/test3/txs/push",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ tx: txHex }),
    }
  );

  const broadcastData = await broadcastResponse.json();
  console.log(broadcastData);```

I don't understand how this is failing. Can i get some help

You can’t add an output after it’s signed. That will invalidate the signature.