Close Menu
  • Home
  • Altcoin
  • Bitcoin
  • Crypto
  • Forex
  • Online Money
What's Hot

7 Reasons Your Card Might Not Work — and What to Do 

April 6, 2026

The Best Trades Will Find You…If You Stop Looking for Them » Learn To Trade The Market

April 6, 2026

GSC Logging Error Yielded Inflated Impressions Since May 2025

April 6, 2026
Facebook X (Twitter) Instagram
  • Altcoin
  • Bitcoin
  • Crypto
  • Forex
  • Online Money
Facebook X (Twitter) Instagram
Cointelegraphe
  • Home
  • Altcoin
  • Bitcoin
  • Crypto
  • Forex
  • Online Money
Cointelegraphe
Home»Bitcoin»bitcoinjs – Create Bitcoin Transaction: Need validator function to validate signatures
bitcoinjs – Create Bitcoin Transaction: Need validator function to validate signatures
Bitcoin

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

adminBy adminApril 16, 2025No Comments3 Mins Read
Share
Facebook Twitter LinkedIn Pinterest Email


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

bitcoin BitcoinJS create Function signatures transaction validate validator
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
admin
  • Website

Related Posts

7 Reasons Your Card Might Not Work — and What to Do 

April 6, 2026

Kiyosaki Says 1974 Shift Drives Debt Crisis, Backs Bitcoin and gold

April 5, 2026

Who Is Really Selling Bitcoin? Analyst Uncovers The On-chain Dynamics 

April 4, 2026

This Analyst Thinks Bitcoin’s 50% Crash Was A ‘Victory’

April 3, 2026
Add A Comment
Leave A Reply Cancel Reply

Top Insights

7 Reasons Your Card Might Not Work — and What to Do 

April 6, 2026

The Best Trades Will Find You…If You Stop Looking for Them » Learn To Trade The Market

April 6, 2026

GSC Logging Error Yielded Inflated Impressions Since May 2025

April 6, 2026

Polymarket just revealed a ‘full exchange upgrade’ to take control of its own trading and truth

April 6, 2026
ads

Subscribe to Updates

Get the latest creative news from Cointelegraphe about Crypto, bItcoin and Altcoin.

About Us
About Us

At CoinTelegraphe, we are dedicated to bringing you the latest and most insightful news, analysis, and updates from the dynamic world of cryptocurrency. Our mission is to provide our readers with accurate, timely, and comprehensive information to help them navigate the complexities of the crypto market.

Facebook X (Twitter) Instagram Pinterest YouTube
Top Insights

7 Reasons Your Card Might Not Work — and What to Do 

April 6, 2026

The Best Trades Will Find You…If You Stop Looking for Them » Learn To Trade The Market

April 6, 2026

GSC Logging Error Yielded Inflated Impressions Since May 2025

April 6, 2026
Get Informed

Subscribe to Updates

Get the latest creative news from Cointelegraphe about Crypto, bItcoin and Altcoin.

Please enable JavaScript in your browser to complete this form.
Loading
  • About us
  • Contact Us
  • Shop
  • Privacy Policy
  • Terms and Conditions
Copyright 2024 Cointelegraphe Design By Horaam Sultan.

Type above and press Enter to search. Press Esc to cancel.