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!

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)
);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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