3

How can I create a raw transaction when I'm given the input scripts, input indexes, input txids, output script, output address and output amount? The method below works but it requires the method Transaction setHash to be public which it is not. Can I get what I want without having to make any changes to Bitcoinj?

    NetworkParameters params = MainNetParams.get();
    Transaction tx = new Transaction(params);
    tx.addOutput(Coin.ZERO, new Script(HEX.decode(outputScript)));
    try {
        Address addr = new Address(params, toAddress);
        tx.addOutput(Coin.valueOf(toAmount), addr);
    } catch (AddressFormatException name) {
        return null;
    }

    Script script = new Script(HEX.decode(inputScript));
    Address addr = new Address(params, script.getPubKeyHash());

    Transaction parentTx = new Transaction(params);
    for (int j = 0; j < inputIndex; j++) {
        parentTx.addOutput(new TransactionOutput(params, parentTx, Coin.ZERO, addr));
    }
    parentTx.addOutput(new TransactionOutput(params, parentTx, Coin.ZERO, addr));
    parentTx.setHash(Sha256Hash.wrap(txid)); // requires setHash method to be public
    try {
        ECKey key = new DumpedPrivateKey(params, privateKey).getKey();
        tx.addSignedInput(parentTx.getOutput(inputIndex), key);
    } catch (AddressFormatException name) {
        return null;
    }
    return HEX.encode(tx.bitcoinSerialize());
1
  • What is inputScript and txid? Commented Aug 18, 2020 at 12:47

1 Answer 1

2
+50

Don't build the entire parent transaction, just build the outpoint, which is all that is relevant for encoding a transaction to hex. Specifically use this constructor

EDIT: More specifically, cannot recreate the parent transaction unless you have ALL relevant information for that transaction (inputs, locktime, outputs etc..). To use the constructor I linked below you will need to also provide the output index of the output you are spending on your parent transaction.

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.