0

I'm trying to create and sign a Bitcoin transaction using BitcoinJS on the testnet. However, I'm encountering an error when trying to sign the transaction:

Error: Can not sign for this input with the key 03ac517991619c9413d3f886f62feb41eea6c571c7ab3e3f61ef770f63667dd94f

Below is my code:

import * as bitcoin from "bitcoinjs-lib";
import ECPairFactory from 'ecpair';
import ecc from '@bitcoinerlab/secp256k1';

bitcoin.initEccLib(ecc)
const ECPair = ECPairFactory(ecc);


const network = bitcoin.networks.testnet

async function createTransaction(
    privateKeyWIF: string,
    previousTxid: string,
    receiverAddress: string,
    previousHex: string
) {

    const keyPair = ECPair.fromWIF(privateKeyWIF, network);


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

    txb.setVersion(2);
    txb.setLocktime(0);

    txb.addInput({
        hash: previousTxid,
        index: 0,
        nonWitnessUtxo: Buffer.from(previousHex, 'hex'),
    });

    txb.addOutput({
        script: Buffer.from(receiverAddress, 'hex'),
        value: 200,
    }); // Sending 0.000002 BTC


    txb.signInput(0, keyPair);
    txb.finalizeAllInputs();

    const tx = txb.extractTransaction();
    return tx.toHex();
}


const main = () => {
    const privateKeyWIF = "..." // my WIF private from UniSat wallet
    const previousTxid = '1e1f8daf5b1c520dbe251e4919d84e105f1a9ac3446e563998e0fca8871c250c'
    const receiver = 'tb1pfjvvn8x9fy5c5ppzrq729tyhu04pneyumukvmnqw78vwugpyatgq5yvxlw'
    const previosHex = '02000000000101804daa67aaf86c2fb8bb4ec428a2c8bbba1bd8f5e339fc3fb4d833b4322d25050200000000fdffffff092413000000000000225120d8c1604c1fac7bee40557fa76ba914c53136884e53f773440ec07d6415582639401f000000000000160014fdeb0cc3ea41a5ea4d5091081f6ba0af45528de0e80300000000000022512093024cb7d0600390806e993501c0bd1e9d200294a78e8daa79216e85833c45b8e803000000000000160014f0ee163efef8683a698c4646daf43ab71f0ff86c8895842700000000225120e30c3aa0f4b649b92e5e870f25d5c550a5df9f2fa4212ab9855c90c1ef90443cb036000000000000160014d5067f147f863ba8e152e54153c54a395a5baf3ed0070000000000002251204c41cc5cb6714b5b56d98032fa2cae97dfe9cd0da0b8c9b27c1bd1458148cd13a00f000000000000160014e583eec876ac45747804ed04b02fd4d4cd07f49c2413000000000000160014e22059700d76c7b564c9b8d4996d24c0adffaffa01406aab69d3bfdf2877ed12a8ea4f0aae67e4d17df782f827c750e5299a09e171ccea960b6e8ac94916f2083d03321e672ceff4dd6ed33833ef4e1b9662bfa3044b26bf2b00'

    createTransaction(privateKeyWIF, previousTxid, receiver, previosHex)
        .then((transactionHex) => {
            console.log('Transaction Hex:', transactionHex);
        })
        .catch((error) => {
            console.error('Error:', error.message);
        });
}

main()
1
  • 1
    One problem I see immediately is that you're parsing an address as a hexadecimal string. Commented Jul 9 at 15:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.