How do we verify the signature on a raw transaction using Bitcoinj?

2

I managed to create a raw tx using Bitcoinj but not able to figure out how to verify its signatures. Assuming I know the addresses corresponding to the (supposedly) unspent outputs used as inputs to the Tx, what is the easiest way to verify the Tx?

Jus12

Posted 2015-01-07T15:08:08.553

Reputation: 1 243

Answers

4

You're interested in the following API calls:

public List<TransactionInput> Transaction.getInputs()
public Script TransactionInput.getScriptSig() throws ScriptException
public void Script.correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey)

Use them like so:

Transaction tx = ...
List<TransactionInput> inputs = tx.getInputs();
for(int i = 0; i < inputs.size(); i++) {
    TransactionInput input = inputs.get(i);
    Script scriptSig = input.getScriptSig();
    Script scriptPubKey = ...
    scriptSig.correctlySpends(tx, i, scriptPubKey);
}

The tricky bit is getting scriptPubKey. If you have the transactions you're spending in memory, it's as simple as input.getConnectedOutput().getScriptPubKey();

If it isn't, then you can make an educated guess by converting the address to a P2PKH scriptPubKey.

public static Script ScriptBuilder.createOutputScript(Address to)

This creates an edge case where if someone tries to spend a P2PK output, it will appear to be signed incorrectly to your program. (Both are represented by addresses.)

Nick ODell

Posted 2015-01-07T15:08:08.553

Reputation: 26 536

Seems to answer the question. Will check and revert. Thanks for mentioning the P2PK outputs. The transactions are created by me and are standard so I can probably ignore this.Jus12 2015-01-08T05:22:19.333

correctlySpends requires a 4th boolean parameter (enforceP2SH). What is that?Jus12 2015-01-11T05:07:31.767

@Jus12 It's for implementing a rare edge case of BIP0016. Set it to true. P.S. You are using an old version of BitcoinJ. You should update it.

Nick ODell 2015-01-11T05:17:57.123

Thanks. I set it to true. There are significant changes from 0.11 to 0.12. I tried to upgrade but it breaks my code (requires some refactoring). Will get to it eventually. Are there any serious issues in using 0.11?Jus12 2015-01-12T05:18:58.400

@Jus12 I tried to upgrade but it breaks my code (requires some refactoring) Ah, fair enough. Are there any serious issues in using 0.11? Well, people on the internet will assume you're using the latest version. :) But there's nothing specific I can think of.Nick ODell 2015-01-12T05:22:49.597

1

As an update, there are actually some serious in using 0.11 based on this bug report: https://github.com/bitcoinj/bitcoinj/issues/1082

Jus12 2015-10-15T07:07:41.680