• About
  • FAQ
  • Earn Bitcoin while Surfing the net
  • Buy & Sell Crypto on Paxful
Newsletter
Approx Foundation
  • Home
    • Home – Layout 1
  • Bitcoin
  • Ethereum
  • Regulation
  • Market
  • Blockchain
  • Business
  • Guide
  • Contact Us
No Result
View All Result
  • Home
    • Home – Layout 1
  • Bitcoin
  • Ethereum
  • Regulation
  • Market
  • Blockchain
  • Business
  • Guide
  • Contact Us
No Result
View All Result
Approx Foundation
No Result
View All Result
Home Bitcoin

bitcoinjs – Create Bitcoin Transaction: Need validator function to validate signatures

Moussa by Moussa
April 18, 2025
in Bitcoin
0
peer discovery – how to obtain the IP addresses of nodes for mining pools?
189
SHARES
1.5k
VIEWS
Share on FacebookShare on Twitter


I am trying to send the bitcoin with my private key using the script and the bitcoinjs-lib. I am constantly getting the error Need validator function to validate signatures over the line when I call const isValid = psbt.validateSignaturesOfAllInputs();.

I am not able to figure out how to resolve this,

const ecc = require('tiny-secp256k1');
const ECPairFactory = require('ecpair').default;
const ECPair = ECPairFactory(ecc);
const axios = require('axios');

const NETWORK = bitcoin.networks.testnet
// const network = bitcoin.networks.testnet; // Or bitcoin.networks.bitcoin for mainnet
const sender_address = "tb1qmrhvnv0w6p9asunmsua3ua829artanps6jfza7"; // Replace with your address
const PRIVATE_KEY_WIF = "PRIVATE_KEY"; 
const DESTINATION_ADDRESS = "mggvPKgz8UJu6sWWdxwPKLKYoyHKhJGzCY"; 
const FEE = 1000; 

async function sendBitcoin() {
    try {
        // Import private key
        const keyPair = ECPair.fromWIF(PRIVATE_KEY_WIF, NETWORK);

        // Generate the address (Native SegWit - P2WPKH)
        const { address } = bitcoin.payments.p2wpkh({
            pubkey: Buffer.from(keyPair.publicKey),
            network: NETWORK,
        });
        console.log(`Sending from: ${address}`);

        // Fetch UTXOs for the address
        const utxos = await getUtxos();
        console.log(`Fetched UTXOs:`, utxos);

        if (!Array.isArray(utxos) || utxos.length === 0) {
            throw new Error("No UTXOs available for the given address.");
        }

        // Create a new PSBT
        const psbt = new bitcoin.Psbt({ network: NETWORK });
        console.log(`Initialized PSBT:`, psbt);

        let totalInput = 0;

        // Add inputs from UTXOs
        utxos.forEach((utxo) => {
            console.log(`Adding UTXO: ${JSON.stringify(utxo)}`);
            psbt.addInput({
                hash: utxo.txid,
                index: utxo.vout,
                witnessUtxo: {
                    script: Buffer.from(bitcoin.address.toOutputScript(address, NETWORK)),
                    value: utxo.value,
                },
            });
            totalInput += utxo.value;
        });

        // Calculate the amount to send
        const sendAmount = 2000;
        if (sendAmount <= 0) {
            throw new Error("Insufficient funds after deducting fees.");
        }

        // Add output for destination
        psbt.addOutput({
            address: DESTINATION_ADDRESS,
            value: sendAmount,
        });

        // Add change output if applicable
        const change = totalInput - sendAmount - FEE;
        if (change > 0) {
            const changeAddress = bitcoin.payments.p2wpkh({
                pubkey: Buffer.from(keyPair.publicKey),
                network: NETWORK,
            }).address;
            console.log(`Adding change output: ${changeAddress}`);
            psbt.addOutput({
                address: changeAddress,
                value: change,
            });
        }

        utxos.forEach((_, index) => {
          psbt.signInput(index, {
              publicKey: Buffer.from(keyPair.publicKey),
              sign: (hash) => {
                  const signature = keyPair.sign(hash);
                  return Buffer.from(signature); 
              },
          });
      });

      console.log(`Signed all inputs`);

        const isValid = psbt.validateSignaturesOfAllInputs();
        console.log(`Signatures valid: ${isValid}`);

        psbt.finalizeAllInputs();

        const rawTransaction = psbt.extractTransaction().toHex();
        console.log(`Raw Transaction: ${rawTransaction}`);

        let myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");

        let raw = JSON.stringify({
            "method": "sendrawtransaction",
            "params": [
              rawTransaction
            ]
        });

        let requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: raw,
            redirect: 'follow'
        };

        let quickNodeUrl = "https://abcd-efgh-igkl.btc-testnet.quiknode.pro/6a1xxxxxxxxxxxxxxxxxxxxxxxxx4/";

        fetch(quickNodeUrl, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log("Broadcast Response: ", result);
            })
            .catch(error => console.log('Error broadcasting transaction:', error));

    } catch (error) {
        console.error(`Error: ${error.stack}`);
    }
}

sendBitcoin();

async function getUtxos() {
    try {
        const response = await axios.get(`https://blockstream.info/testnet/api/address/${sender_address}/utxo`);
        return response.data;
    } catch (error) {
        console.error(`Error fetching UTXOs: ${error.message}`);
        return [];
    }
  } ```.   
Stack Trace Error:
``` Error: Need validator function to validate signatures
    at Psbt._validateSignaturesOfInput (/Users/harshkushwah/Desktop/Btc_Tx_Listener/node_modules/bitcoinjs-lib/src/psbt.js:424:13)
    at Psbt.validateSignaturesOfInput (/Users/harshkushwah/Desktop/Btc_Tx_Listener/node_modules/bitcoinjs-lib/src/psbt.js:416:17)
    at /Users/harshkushwah/Desktop/Btc_Tx_Listener/node_modules/bitcoinjs-lib/src/psbt.js:404:12
    at Array.map ()
    at Psbt.validateSignaturesOfAllInputs (/Users/harshkushwah/Desktop/Btc_Tx_Listener/node_modules/bitcoinjs-lib/src/psbt.js:403:52)
    at sendBitcoin (/Users/harshkushwah/Desktop/Btc_Tx_Listener/transfer-seqWit.js:93:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) ```



Source link

Related articles

Michael Saylor vs. Peter Schiff: Is the MicroStrategy Bitcoin Bet at Risk?

Michael Saylor vs. Peter Schiff: Is the MicroStrategy Bitcoin Bet at Risk?

April 30, 2026
Analyst Says XRP Fundamentals Are Accelerating, What Does This Mean?

Analyst Says XRP Fundamentals Are Accelerating, What Does This Mean?

April 30, 2026
Share76Tweet47

Related Posts

Michael Saylor vs. Peter Schiff: Is the MicroStrategy Bitcoin Bet at Risk?

Michael Saylor vs. Peter Schiff: Is the MicroStrategy Bitcoin Bet at Risk?

by Moussa
April 30, 2026
0

Peter Schiff is back with receipts, and this time the numbers are harder to dismiss. The longtime gold advocate and...

Analyst Says XRP Fundamentals Are Accelerating, What Does This Mean?

Analyst Says XRP Fundamentals Are Accelerating, What Does This Mean?

by Moussa
April 30, 2026
0

Trusted Editorial content, reviewed by leading industry experts and seasoned editors. Ad Disclosure The XRP price has been on a...

WLFI Selloff Deepens After Controversial Governance Vote Goes Live

WLFI Selloff Deepens After Controversial Governance Vote Goes Live

by Moussa
April 30, 2026
0

World Liberty Financial’s native token WLFI lost roughly 17% of its value on Wednesday as a governance proposal affecting more...

Strategy And Blockstream CEOs Paint Vision Of Bitcoin’s Financial Future

Strategy And Blockstream CEOs Paint Vision Of Bitcoin’s Financial Future

by Moussa
April 30, 2026
0

Strategy CEO Phong Le and Blockstream CEO Adam Back appeared Wednesday on a panel moderated by Natalie Brunell, covering Bitcoin...

BYDFi Reviews 6th Anniversary with Prediction Market Launch

BYDFi Reviews 6th Anniversary with Prediction Market Launch

by Moussa
April 30, 2026
0

PRESS RELEASE. VICTORIA, Seychelles, April 30, 2026 – Global crypto exchange BYDFi is approaching the close of its month-long 6th...

Load More

youssufi.com

sephina.com

[vc_row full_width="stretch_row" parallax="content-moving" vc_row_background="" background_repeat="no-repeat" background_position="center center" footer_scheme="dark" css=".vc_custom_1517813231908{padding-top: 60px !important;padding-bottom: 30px !important;background-color: #191818 !important;background-position: center;background-repeat: no-repeat !important;background-size: cover !important;}" footer_widget_title_color="#fcbf46" footer_button_bg="#fcb11e"][vc_column width="1/4"]

We bring you the latest in Crypto News

[/vc_column][vc_column width="1/4"][vc_wp_categories]
[/vc_column][vc_column width="1/4"][vc_wp_tagcloud taxonomy="post_tag"][/vc_column][vc_column width="1/4"]

Newsletter

[vc_raw_html]JTNDcCUzRSUzQ2RpdiUyMGNsYXNzJTNEJTIydG5wJTIwdG5wLXN1YnNjcmlwdGlvbiUyMiUzRSUwQSUzQ2Zvcm0lMjBtZXRob2QlM0QlMjJwb3N0JTIyJTIwYWN0aW9uJTNEJTIyaHR0cHMlM0ElMkYlMkZhcHByb3gub3JnJTJGJTNGbmElM0RzJTIyJTNFJTBBJTBBJTNDaW5wdXQlMjB0eXBlJTNEJTIyaGlkZGVuJTIyJTIwbmFtZSUzRCUyMm5sYW5nJTIyJTIwdmFsdWUl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VsZCUyMHRucC1maWVsZC1idXR0b24lMjIlM0UlM0NpbnB1dCUyMGNsYXNzJTNEJTIydG5wLXN1Ym1pdCUyMiUyMHR5cGUlM0QlMjJzdWJtaXQlMjIlMjB2YWx1ZSUzRCUyMlN1YnNjcmliZSUyMiUyMCUzRSUwQSUzQyUyRmRpdiUzRSUwQSUzQyUyRmZvcm0lM0UlMEElM0MlMkZkaXYlM0UlM0NiciUyRiUzRSUzQyUyRnAlM0U=[/vc_raw_html][/vc_column][/vc_row]
No Result
View All Result
  • Contact Us
  • Homepages
  • Business
  • Guide

© 2024 APPROX FOUNDATION - The Crypto Currency News