<pre class="lang-javascript prettyprint-override"><code>
        utxos.forEach((_, index) =&gt; {
            psbt.signInput(index, {
                publicKey: Buffer.from(keyPair.publicKey),
                sign: (hash) =&gt; {
                    const signature = keyPair.sign(hash);
                    return Buffer.from(signature); 
                },
            });
        });
</code></pre>
<p>Replacing the pstb.signInput() with the above resolved the error</p>

CC BY-SA 4.0
2024-12-26T11:17:44.153Z
2024-12-26T11:19:03.120Z
2024-12-26T11:19:03.120Z
Priyanshu
<p>I am trying to send the bitcoin with my private key using the script and the <code>bitcoinjs-lib</code>. I am constantly getting the error <code>Expected property &quot;signature&quot; of type Buffer, got Uint8Array</code> over the line when I call <code>pstb.signInput()</code>.</p>
<p>I am not able to figure out how to resolve this,</p>
<pre class="lang-javascript prettyprint-override"><code>const bitcoin = require('bitcoinjs-lib');
const ecc = require('tiny-secp256k1');
const ECPairFactory = require('ecpair').default;
const ECPair = ECPairFactory(ecc);
const { getUtxos } = require('./utxo');

const NETWORK = bitcoin.networks.bitcoin
const PRIVATE_KEY_WIF = &quot;PRIVATE_KEY&quot;; 
const DESTINATION_ADDRESS = &quot;bc1q9es00454u6n49ullgg2cyh23prpglpees5ptyc&quot;; 
const FEE = 1500; 

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(&quot;No UTXOs available for the given address.&quot;);
        }

        // 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) =&gt; {
            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 = 5000;
        if (sendAmount &lt;= 0) {
            throw new Error(&quot;Insufficient funds after deducting fees.&quot;);
        }

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

        // Add change output if applicable
        const change = totalInput - sendAmount - FEE;
        if (change &gt; 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) =&gt; {
            console.log(`Signing input at index: ${index}`);
            psbt.signInput(index, keyPair);
        });

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

        psbt.finalizeAllInputs();

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

        console.log('Transaction ready to broadcast:', rawTransaction);

        const broadcastResponse = await axios.post('https://blockstream.info/api/tx', rawTransaction);
        console.log(`Transaction successfully broadcasted. TXID: ${broadcastResponse.data}`);
    } catch (error) {
        console.error(`Error: ${error.stack}`);
    }
}

sendBitcoin();

</code></pre>
<p>If required, the below is the package version list:</p>
<pre class="lang-json prettyprint-override"><code>{
  &quot;dependencies&quot;: {
    &quot;@mempool/mempool.js&quot;: &quot;^2.3.0&quot;,
    &quot;axios&quot;: &quot;^1.7.9&quot;,
    &quot;bip32&quot;: &quot;^5.0.0-rc.0&quot;,
    &quot;bip39&quot;: &quot;^3.1.0&quot;,
    &quot;bitcoinjs-lib&quot;: &quot;^6.1.7&quot;,
    &quot;bs58&quot;: &quot;^6.0.0&quot;,
    &quot;ecpair&quot;: &quot;^3.0.0-rc.0&quot;,
    &quot;hdkey&quot;: &quot;^2.1.0&quot;,
    &quot;tiny-secp256k1&quot;: &quot;^2.2.3&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;dotenv&quot;: &quot;^16.4.7&quot;
  }
}
</code></pre>
<p>Stack Trace Error:</p>
<pre><code>Error: Error: Expected property &quot;signature&quot; of type Buffer, got Uint8Array
    at captureStackTrace (/home/self-cutodial-wallet/node_modules/typeforce/errors.js:20:11)
    at tfSubError (/home/self-cutodial-wallet/node_modules/typeforce/errors.js:99:3)
    at _object (/home/self-cutodial-wallet/node_modules/typeforce/index.js:117:15)
    at typeforce (/home/self-cutodial-wallet/node_modules/typeforce/index.js:233:9)
    at typeforce (/home/self-cutodial-wallet/node_modules/typeforce/index.js:239:10)
    at Object.encode (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/script_signature.js:63:3)
    at Psbt._signInput (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/psbt.js:679:38)
    at Psbt.signInput (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/psbt.js:648:17)
    at /home/self-cutodial-wallet/gg.js:82:18
    at Array.forEach (&lt;anonymous&gt;)
    ```
</code></pre>

CC BY-SA 4.0
2024-12-24T13:36:37.060Z
Hi Priyanshu, can you also include the stack trace of the error?
Vojtěch Strnad
CC BY-SA 4.0
2024-12-26T05:01:47.740Z
Hi Vojtech, I have added the stack trace error in the post. Thank you for checking out !!
Priyanshu
<script><sending><bitcoinjs>
Sending Bitcoin: Expected property "signature" of type Buffer, got Uint8Array
Priyanshu
# Sending Bitcoin: Expected property "signature" of type Buffer, got Uint8Array

(Asked by: username_0 on 2024-12-24)

I am trying to send the bitcoin with my private key using the script and the bitcoinjs-lib. I am constantly getting the error Expected property "signature" of type Buffer, got Uint8Array over the line when I call pstb.signInput().
I am not able to figure out how to resolve this,
const bitcoin = require('bitcoinjs-lib');
const ecc = require('tiny-secp256k1');
const ECPairFactory = require('ecpair').default;
const ECPair = ECPairFactory(ecc);
const { getUtxos } = require('./utxo');

const NETWORK = bitcoin.networks.bitcoin
const PRIVATE_KEY_WIF = "PRIVATE_KEY"; 
const DESTINATION_ADDRESS = "bc1q9es00454u6n49ullgg2cyh23prpglpees5ptyc"; 
const FEE = 1500; 

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 = 5000;
        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) => {
            console.log(`Signing input at index: ${index}`);
            psbt.signInput(index, keyPair);
        });

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

        psbt.finalizeAllInputs();

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

        console.log('Transaction ready to broadcast:', rawTransaction);

        const broadcastResponse = await axios.post('https://blockstream.info/api/tx', rawTransaction);
        console.log(`Transaction successfully broadcasted. TXID: ${broadcastResponse.data}`);
    } catch (error) {
        console.error(`Error: ${error.stack}`);
    }
}

sendBitcoin();


If required, the below is the package version list:
{
  "dependencies": {
    "@mempool/mempool.js": "^2.3.0",
    "axios": "^1.7.9",
    "bip32": "^5.0.0-rc.0",
    "bip39": "^3.1.0",
    "bitcoinjs-lib": "^6.1.7",
    "bs58": "^6.0.0",
    "ecpair": "^3.0.0-rc.0",
    "hdkey": "^2.1.0",
    "tiny-secp256k1": "^2.2.3"
  },
  "devDependencies": {
    "dotenv": "^16.4.7"
  }
}

Stack Trace Error:
Error: Error: Expected property "signature" of type Buffer, got Uint8Array
    at captureStackTrace (/home/self-cutodial-wallet/node_modules/typeforce/errors.js:20:11)
    at tfSubError (/home/self-cutodial-wallet/node_modules/typeforce/errors.js:99:3)
    at _object (/home/self-cutodial-wallet/node_modules/typeforce/index.js:117:15)
    at typeforce (/home/self-cutodial-wallet/node_modules/typeforce/index.js:233:9)
    at typeforce (/home/self-cutodial-wallet/node_modules/typeforce/index.js:239:10)
    at Object.encode (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/script_signature.js:63:3)
    at Psbt._signInput (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/psbt.js:679:38)
    at Psbt.signInput (/home/self-cutodial-wallet/node_modules/bitcoinjs-lib/src/psbt.js:648:17)
    at /home/self-cutodial-wallet/gg.js:82:18
    at Array.forEach ()
    ```

**Tags:** script, sending, bitcoinjs

> **Comments:**
> **username_1**: Hi username_0, can you also include the stack trace of the error?  
> **username_0**: Hi Vojtech, I have added the stack trace error in the post. Thank you for checking out !!  

---

## 1 answers

### Answer by username_0 on 2024-12-26. Score: 1 | Accepted answer

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

Replacing the pstb.signInput() with the above resolved the error


---

