uncooked transaction – signal native P2WPKH with bitcoinjs-lib (signing sighash) (non-mandatory-script-verify-flag)

i experimented rather a lot with p2wsh multisig configurations with bitcoinjs-lib. however when i attempted to signal a typical native segwit p2wpkh to p2wpkh transaction every thing goes okay aside from bitcoin-cli sendrawtransaction. it says

non-mandatory-script-verify-flag (Signature have to be zero for failed CHECK(MULTI)SIG operation)

js code (./btc is right here, the remaining will be npm set uped):

const { btc, ship, listunspent, getnewaddress, bech32toScriptPubKey } = require('./btc')();
const bitcoin = require('bitcoinjs-lib');
const community = bitcoin.networks.testnet;
const hashtype = bitcoin.Transaction.SIGHASH_ALL;
const ECPair = require('ecpair').ECPairFactory(require('tiny-secp256k1'));
const readline = require('readline');

const rl = readline.createInterface({
    enter: course of.stdin,
    output: course of.stdout

rl.on('shut', () => course of.exit(0));

const enter = q => new Promise(r => rl.query(q, r));


async operate essential() {
    const u = (await listunspent(0, 0, true)).filter(x => x.solvable && x.spendable && x.desc.startsWith('wpkh'));


    const v = await enter('Which enter to make use of? ');

    const utxo = u[parseInt(v)];

    if (!utxo) {
        course of.exit(1);

    var out = await enter('Output deal with (depart empty to generate a brand new one) ');

    if (out.size == 0) {
        out = await getnewaddress();

    if (out.size != 42) {
        console.log('p2wpkh addresses are 42 chars lengthy');
        course of.exit(1);

    const ecpair = ECPair.fromWIF(await btc('dumpprivkey', utxo.deal with), community);

    const tx = new bitcoin.Transaction(community);

    tx.addInput(Buffer.from(utxo.txid, 'hex').reverse(), utxo.vout);

    const price = 110;

    tx.addOutput(bech32toScriptPubKey(out), utxo.quantity - price);

    const sighash = tx.hashForWitnessV0(
        0, Buffer.from(utxo.scriptPubKey, 'hex'), utxo.quantity, hashtype

    tx.setWitness(0, [
        bitcoin.script.signature.encode(ecpair.sign(sighash), hashtype),

    console.log(await ship(tx.toHex()));

TX hex


i believe i’m making a mistake in what have to be included within the sighash. What scriptPubKey is used within the sighash of a p2wpkh?

Leave a Reply

Your email address will not be published. Required fields are marked *