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) ```