<p>From error message, I guess you sign your transaction in a same way when spend legacy address, because it literally means your script sig is not empty(it must be empty for segwit spend as script sig must be placed into witness stack). I don't think it would be problem with bitcore-lib, but you might use my open source <a href="https://www.npmjs.com/package/bitcoin-sdk-js" rel="nofollow noreferrer"><code>bitcoin-sdk-js</code></a> as an alternative as it supports segwit spend.</p>
<p>Below code works.</p>
<pre class="lang-javascript prettyprint-override"><code>import * as bitcoin from 'bitcoin-sdk-js';

const privkey =
  'e6c58327b4bf1314296bba7adb66f94c36ea5611ac07830c229aa7ee6f9caac3';
const toAddress = 'tb1qmjqyknun9umlwlle5nuy8jz9ms7v85cp7k2nfe';
const toValue = 300000;
const txHash =
  '8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf';
const inputValue = 310981;

const tx = new bitcoin.Transaction();

await tx.addInput({
  txHash: txHash,
  index: 1,
  value: inputValue,
});
await tx.addOutput({
  address: toAddress,
  value: toValue,
});
await tx.signInput(privkey, 0);

const txHex = await tx.getSignedHex();

</code></pre>

CC BY-SA 4.0
2024-05-17T07:58:10.847Z
here is the raw hex
02000000017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b37010000006a47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883ffffffff029065000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30164f20300000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58500000000

and the error is
mandatory-script-verify-flag-failed (Witness requires empty scriptSig),

checking on this pkg, will keep you updated.
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T08:37:31.623Z
As I guessed you are trying to spend segwit output in a legacy way(which is wrong). You must move script sig part(which is `47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883`) to witness stack(at the end of tx hex) and also need to add segwit flag, mark and witness item count. I think the signature itself would be also wrong as the segwit message to sign is different from legacy. You can check BIP143 for specific semantic.
Hyunhum Cho
CC BY-SA 4.0
2024-05-17T09:06:37.623Z
brother, i dont understand all these that much, I just want a tool or pacakge to work, and i will only provide the payload which is 

{
   address: 'tb1qj5vw4zugaqhg9kgq873lw5vwz5vqe3v9uldtdu',
   privateKey: 'L4xJPRKG4QpqeFraSqJQiY6iPd364H8E9jrmtZkqVw2WQVCejBcj',
   recipientAddress: 'tb1qmjqyknun9umlwlle5nuy8jz9ms7v85cp7k2nfe',
   satoshis: 26000,
   chain: 'testnet'
}

and the code should give me hex which works. the package you shared doesn't have a proper doc, and code is also outdated. anyways I'll try to make it work. thanks for the time.
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T09:34:40.343Z
I'm sorry I just pushed tx to testnet for test accidentally with the private key you provided and it works well. I edited my answer with code.
If you need testnet btc let me know I will send to you.
Hyunhum Cho
CC BY-SA 4.0
2024-05-17T10:20:54.290Z
Hi Hyunhum, that's really great that this code works I also want to try this but i have nothing left unspent, i have tried many faucets but haven't received any yet, can you please send me back?
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T10:41:11.397Z
I have tried this code although not sure about how you fetched priv key from wif, i have used bitcoinjs-lib for that, the hex it generates is giving me bad-txns-inputs-missingorspent
error, hex is: 010000000001017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b370100000000fdffffff0190650000000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58502483045022100d4f0c6e6b5fdca9839a3a75f1f9daaa6c9d083c57bd731d6a78f0d5f448bc6de02205015a6b67abde663f7772e4c499e43ad920de5d4ac447c274ceb49bcfcb53be8012103cc5b73e26e04b2e9cb71723f7669ff611127e219fd14ad522c649272faef8a7500000000
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T10:47:33.860Z
because that tx is already broadcasted by me(in other words it is spent). I will send u test btc. u can try with unspent transaction
Hyunhum Cho
CC BY-SA 4.0
2024-05-17T10:48:45.707Z
No actully I have now tried with difftrent account where the utxo is left, but still get this error.
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T11:04:40.970Z
No you didn't have utxo left as you can see https://blockstream.info/testnet/address/tb1qj5vw4zugaqhg9kgq873lw5vwz5vqe3v9uldtdu

I sent you same amount in transaction id [`8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf`](https://blockstream.info/testnet/tx/8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf), try using this
Hyunhum Cho
CC BY-SA 4.0
2024-05-17T11:14:37.377Z
Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/153168/discussion-between-hyunhum-and-sudhanshu-sinha).
Hyunhum Cho
CC BY-SA 4.0
2024-05-17T11:14:40.297Z
I have tried it with this account also it sends me a hex:
010000000001017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b370100000000fdffffff01803e000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30102473044022048f3104cb19a1f2f61cae8c40a6f6d7ec1d9bbb117a918533e852bfc54b6eaab022077c24324009bae1db18ed73c1e4c5fe03d54a2c89e63ff58fb4839fb7829d36d01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a88300000000

and when I pass this in node method sendrawtransaction it returns {"bad-txns-inputs-missingorspent"} error. can you please help me to debug this, thanks
Sudhanshu Sinha
CC BY-SA 4.0
2024-05-17T07:36:28.667Z
2024-05-28T13:56:45.220Z
2024-05-28T13:56:45.220Z
Hyunhum Cho
<p>So I am using this NPM package ( <a href="https://www.npmjs.com/package/bitcore-lib" rel="nofollow noreferrer">https://www.npmjs.com/package/bitcore-lib</a> )
to create and sign a Bitcoin legacy transaction locally and it was working fine for legacy.
But when I tried to do the same for segwit addresses I started getting this error when i submit that raw into sendrawtransasction node method.</p>
<pre><code>mandatory-script-verify-flag-failed (Witness requires empty scriptSig)
</code></pre>
<p>So I think the issue is with this package as the structure of this payment is not what is required for a SegWit transaction.</p>
<p>So my main question is is there any package in javascript I can use to create and sign a transaction? the main payload I have is</p>
<pre><code>receipentAddress, senderAddress, amount ( in satoshis ), and privateKey in WIF. 
</code></pre>
<p>any help or clue is highly appreciated.</p>
<p>//edit:</p>
<p>rawhex:</p>
<pre><code>02000000017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b37010000006a47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883ffffffff029065000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30164f20300000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58500000000
</code></pre>
<p>edit: added code below</p>
<pre><code>const axios = require('axios');
const bitcore = require('bitcore-lib');

async function generateAndSignTransaction(payload) {
  let { address, privateKey, recipientAddress, satoshis, chain } = payload;

  try {
    async function fees() {
      try {
        let key;
        if (chain === &quot;testnet&quot;){
          key = 'test3'
        }else {
          key = 'main'
        }

        let r = await axios.get(`https://api.blockcypher.com/v1/btc/${key}`);
        let feeObj = new Object;
        feeObj[&quot;High_fee&quot;] = r.data.high_fee_per_kb;
        feeObj[&quot;Medium_fee&quot;] = r.data.medium_fee_per_kb;
        feeObj[&quot;Low_fee&quot;] = r.data.low_fee_per_kb;
        return feeObj;
      } catch (error) {
        console.error(error);
        throw error; // Propagate error
      }
    }


    let res = await fees();
    let fee = res.Low_fee;


    let url = `https://blockstream.info/${chain}/api/address/${address}/utxo`;
    res = await axios.get(url);

    console.log('UTXOS: ', res.data);


    let i = 0;
    let utxos = [];
    let balance_utxos = 0;

    while (balance_utxos &lt;= satoshis + fee &amp;&amp; i &lt; res.data.length) {
      let utxo = {
        &quot;txId&quot;: res.data[i].txid,
        &quot;outputIndex&quot;: res.data[i].vout,
        &quot;script&quot;: bitcore.Script.buildPublicKeyHashOut(address).toString(),
        &quot;satoshis&quot;: res.data[i].value
      };
      utxos.push(utxo);
      balance_utxos += res.data[i].value;
      i++;
    }
    console.log('UTXOS 02: ', utxos);

    let tx = new bitcore.Transaction();
    tx.from(utxos);
    tx.to(recipientAddress, satoshis);
    tx.change(address);
    tx.fee(fee);
    tx.inputs.forEach(input =&gt; {
      input.setScript(bitcore.Script.empty());
    });
    tx.sign(privateKey);


    console.log('Tramsactopnm: ', tx);
    console.log('Tramsactopnm data: ', tx.serialize());

    let txnHex = tx.toString();

    return { txid: txnHex }; // Return the serialized transaction
  } catch (error) {
    console.error('Error:', error);
    throw error; // Propagate error
  }
}


module.exports = { generateAndSignTransaction };
</code></pre>

<transactions><segregated-witness><nodes><javascript><signrawtransaction>
How to create and sign a segwit transaction using any npm pacakge
Sudhanshu Sinha
# How to create and sign a segwit transaction using any npm pacakge

(Asked by: username_0 on 2024-05-17)

So I am using this NPM package ( <https://www.npmjs.com/package/bitcore-lib> )
to create and sign a Bitcoin legacy transaction locally and it was working fine for legacy.
But when I tried to do the same for segwit addresses I started getting this error when i submit that raw into sendrawtransasction node method.

```
mandatory-script-verify-flag-failed (Witness requires empty scriptSig)

```

So I think the issue is with this package as the structure of this payment is not what is required for a SegWit transaction.

So my main question is is there any package in javascript I can use to create and sign a transaction? the main payload I have is

```
receipentAddress, senderAddress, amount ( in satoshis ), and privateKey in WIF. 

```

any help or clue is highly appreciated.

//edit:

rawhex:

```
02000000017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b37010000006a47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883ffffffff029065000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30164f20300000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58500000000

```

edit: added code below

```
const axios = require('axios');
const bitcore = require('bitcore-lib');

async function generateAndSignTransaction(payload) {
  let { address, privateKey, recipientAddress, satoshis, chain } = payload;

  try {
    async function fees() {
      try {
        let key;
        if (chain === "testnet"){
          key = 'test3'
        }else {
          key = 'main'
        }

        let r = await axios.get(`https://api.blockcypher.com/v1/btc/${key}`);
        let feeObj = new Object;
        feeObj["High_fee"] = r.data.high_fee_per_kb;
        feeObj["Medium_fee"] = r.data.medium_fee_per_kb;
        feeObj["Low_fee"] = r.data.low_fee_per_kb;
        return feeObj;
      } catch (error) {
        console.error(error);
        throw error; // Propagate error
      }
    }

    let res = await fees();
    let fee = res.Low_fee;

    let url = `https://blockstream.info/${chain}/api/address/${address}/utxo`;
    res = await axios.get(url);

    console.log('UTXOS: ', res.data);

    let i = 0;
    let utxos = [];
    let balance_utxos = 0;

    while (balance_utxos <= satoshis + fee && i < res.data.length) {
      let utxo = {
        "txId": res.data[i].txid,
        "outputIndex": res.data[i].vout,
        "script": bitcore.Script.buildPublicKeyHashOut(address).toString(),
        "satoshis": res.data[i].value
      };
      utxos.push(utxo);
      balance_utxos += res.data[i].value;
      i++;
    }
    console.log('UTXOS 02: ', utxos);

    let tx = new bitcore.Transaction();
    tx.from(utxos);
    tx.to(recipientAddress, satoshis);
    tx.change(address);
    tx.fee(fee);
    tx.inputs.forEach(input => {
      input.setScript(bitcore.Script.empty());
    });
    tx.sign(privateKey);

    console.log('Tramsactopnm: ', tx);
    console.log('Tramsactopnm data: ', tx.serialize());

    let txnHex = tx.toString();

    return { txid: txnHex }; // Return the serialized transaction
  } catch (error) {
    console.error('Error:', error);
    throw error; // Propagate error
  }
}

module.exports = { generateAndSignTransaction };

```

**Tags:** transactions, segregated-witness, nodes, javascript, signrawtransaction


---

## 1 answers

### Answer by username_1 on 2024-05-17. Score: 1 | Accepted answer

From error message, I guess you sign your transaction in a same way when spend legacy address, because it literally means your script sig is not empty(it must be empty for segwit spend as script sig must be placed into witness stack). I don't think it would be problem with bitcore-lib, but you might use my open source [`bitcoin-sdk-js`](https://www.npmjs.com/package/bitcoin-sdk-js) as an alternative as it supports segwit spend.

Below code works.

```javascript
import * as bitcoin from 'bitcoin-sdk-js';

const privkey =
  'e6c58327b4bf1314296bba7adb66f94c36ea5611ac07830c229aa7ee6f9caac3';
const toAddress = 'tb1qmjqyknun9umlwlle5nuy8jz9ms7v85cp7k2nfe';
const toValue = 300000;
const txHash =
  '8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf';
const inputValue = 310981;

const tx = new bitcoin.Transaction();

await tx.addInput({
  txHash: txHash,
  index: 1,
  value: inputValue,
});
await tx.addOutput({
  address: toAddress,
  value: toValue,
});
await tx.signInput(privkey, 0);

const txHex = await tx.getSignedHex();

```

> **Comments:**
> **username_0**: here is the raw hex 02000000017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b37010000006a47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883ffffffff029065000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30164f20300000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58500000000  and the error is mandatory-script-verify-flag-failed (Witness requires empty scriptSig),  checking on this pkg, will keep you updated.  
> **username_1**: As I guessed you are trying to spend segwit output in a legacy way(which is wrong). You must move script sig part(which is `47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883`) to witness stack(at the end of tx hex) and also need to add segwit flag, mark and witness item count. I think the signature itself would be also wrong as the segwit message to sign is different from legacy. You can check BIP143 for specific semantic.  
> **username_0**: brother, i dont understand all these that much, I just want a tool or pacakge to work, and i will only provide the payload which is   {    address: 'tb1qj5vw4zugaqhg9kgq873lw5vwz5vqe3v9uldtdu',    privateKey: 'L4xJPRKG4QpqeFraSqJQiY6iPd364H8E9jrmtZkqVw2WQVCejBcj',    recipientAddress: 'tb1qmjqyknun9umlwlle5nuy8jz9ms7v85cp7k2nfe',    satoshis: 26000,    chain: 'testnet' }  and the code should give me hex which works. the package you shared doesn't have a proper doc, and code is also outdated. anyways I'll try to make it work. thanks for the time.  
> **username_1**: I'm sorry I just pushed tx to testnet for test accidentally with the private key you provided and it works well. I edited my answer with code. If you need testnet btc let me know I will send to you.  
> **username_0**: Hi username_1, that's really great that this code works I also want to try this but i have nothing left unspent, i have tried many faucets but haven't received any yet, can you please send me back?  
> **username_0**: I have tried this code although not sure about how you fetched priv key from wif, i have used bitcoinjs-lib for that, the hex it generates is giving me bad-txns-inputs-missingorspent error, hex is: 010000000001017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b370100000000fdffffff0190650000000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58502483045022100d4f0c6e6b5fdca9839a3a75f1f9daaa6c9d083c57bd731d6a78f0d5f448bc6de02205015a6b67abde663f7772e4c499e43ad920de5d4ac447c274ceb49bcfcb53be8012103cc5b73e26e04b2e9cb71723f7669ff611127e219fd14ad522c649272faef8a7500000000  
> **username_1**: because that tx is already broadcasted by me(in other words it is spent). I will send u test btc. u can try with unspent transaction  
> **username_0**: No actully I have now tried with difftrent account where the utxo is left, but still get this error.  
> **username_1**: No you didn't have utxo left as you can see https://blockstream.info/testnet/address/tb1qj5vw4zugaqhg9kgq873lw5vwz5vqe3v9uldtdu  I sent you same amount in transaction id [`8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf`](https://blockstream.info/testnet/tx/8bcd197873dbff5cc67cb3e0b1cbbdf097c7af94b0e9365adecb424e408294bf), try using this  
> **username_1**: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/153168/discussion-between-username_1-and-username_0-username_0).  
> **username_0**: I have tried it with this account also it sends me a hex: 010000000001017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b370100000000fdffffff01803e000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30102473044022048f3104cb19a1f2f61cae8c40a6f6d7ec1d9bbb117a918533e852bfc54b6eaab022077c24324009bae1db18ed73c1e4c5fe03d54a2c89e63ff58fb4839fb7829d36d01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a88300000000  and when I pass this in node method sendrawtransaction it returns {"bad-txns-inputs-missingorspent"} error. can you please help me to debug this, thanks  

---

