1

I want to spend from a segwit address and it has a P2WPH script, I created this transaction just like creating a normal P2PKH transaction, but just changed the address of the input to the segwit address, I don't know if this is correct, and signing this transaction in the following method, but it says script was NOT verified successfully...

Transaction signedtx = signInput(rawtx.getHashAsString(),privkey,rawtx);

    public static Transaction signInput(String hash, String prvKey,Transaction spendTx) {
        ECKey ecKey = ECKey.fromPrivate(Utils.HEX.decode(prvKey));
        ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.wrap(hash));
        TransactionSignature transactionSignature = new TransactionSignature(signature,Transaction.SigHash.ALL,true);
        TransactionWitness witness = TransactionWitness.redeemP2WPKH(transactionSignature,ecKey);
        TransactionInput input = spendTx.getInput(0);
        input.setWitness(witness);
        return spendTx;
    }

I am not very familiar with bitcoinj, and currently there is very little technical guidance related to segwit, I hope someone can help me!

1 Answer 1

0

In general is should be like:

// input index to sign
int index = 0;
// amount to sign (must equal to actual input value)
Coin value = Coin.valueOf(123456);

TransactionSignature signature = tx.calculateWitnessSignature(
   index, 
   prvKey, 
   ScriptBuilder()
      .data(ScriptBuilder.createP2PKHOutputScript(prvKey).program)
      .build(), 
   coin, 
   Transaction.SigHash.ALL, 
   false
);

tx.getInput(index).setScriptSig(ScriptBuilder.createEmpty());
tx.getInput(index).setWitness(
  TransactionWitness.redeemP2WPKH(signature, prvKey)
);
1
  • Most importantly, double-check that your outpoint txids are reversed (to little-endian) the sighash before signing. Maybe BitcoinJ does this for you, but since I never used it I'm not sure if it does. Jan 22 at 7:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.