Given a bitcoin transaction where it is able to redeem it's UTXO's, how can I verify in Java if the signature is actually a valid signature or not. I was trying to use the Bouncy Castle library where I was trying to recreate the message that the private key signs over.

From what I know I need the following things -

1.The version number(4 bytes)
2.The number of Inputs(1 byte)
3.Transaction hash of the input being redeemed
4.Index of the output being redeemed (4 bytes)
5.ScriptPubKey of the output being redeemed prepended with the length of the script
6.Sequence Number(4 bytes)
7.No of outputs we are signing over(1 byte)
8.Total value of the output(8 bytes)
9.ScriptSig for the output prepended with the length
10.locktime field(4 bytes)
11.hashcode type(4 bytes)

I have tried to capture this information from the transaction data but when I try to verify the signature, it fails. Am I missing something?I want to be able to verify if a signature is correct. Thanks.

From what I have read, Step number 5 is a temporary step and the ScriptPubkey is replaced by some other value but I am unable to understand what that value should be.

1 Answer 1


What you described only works for transactions with one input and one output.

In general, what you do is you take the transaction that you want to verify, remove the scriptSigs from all of the inputs, and for the particular input you want, you place in the scriptSig the scriptPubKey (prepended by its length) of the output that input spends. If the output that was spent is P2SH, then you put the redeemScript instead of the scriptPubKey. Then you put the sighash type at the end of the modified transaction.

Once you have that message, you need to hash it with SHA256. Most cryptographic libraries take a message and hash it once. However in Bitcoin, the message is actually hashed twice. So to verify a signature in Bitcoin with a general purpose cryptography library, you need to hash the message first, and then allow the library to hash it again when it verifies.

Lastly, the message is different for inputs that spend Segwit outputs. This message is defined in BIP 143.

  • So in the case where I have one single input spending to two outputs how would this work? Say I hold 500 BTC in one private key and I am sending 200 to Address A, 200 to Address B and 100 to Address C(for sake of simplicity we omit the transaction fee). Then which ScriptPubkey should be put in the scriptSig for input of 500 BTC. @AndrewChow Sep 10, 2019 at 6:37
  • Awesome! I found the bug. I realised that except for the Scripts everything else is stored in little endian format! It works now. Sep 10, 2019 at 10:12

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.