How is the P2SH address obtained in decodescript

2

1

Im trying to understand how to obtain the p2SH address when decoding an output script.

r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));

source

As far as I understand CScriptID is the hash160 of the script.

Albert s

Posted 2016-09-01T21:48:40.030

Reputation: 1 344

Answers

2

So, a P2SH scriptPubKey looks like this:

OP_HASH160 <20 byte script hash> OP_EQUAL

Serialized, in hex, that looks like:

17a9140000000000000000000000000000000000000087

^ ScriptPubkey len 
  ^ OP_HASH160
    ^ Data element len
      ^ Data element
                                            ^ OP_EQUAL

where the zeros can be any byte.

How does that transform into an address starting with 3? You transform it the same way you would a normal Bitcoin address, but with a different version byte. Instead of 00, you would use 05.

See also the P2SH address specification.

Nick ODell

Posted 2016-09-01T21:48:40.030

Reputation: 26 536

please see follow-up here

Albert s 2016-09-02T17:39:53.217

do you transform just the data element?Albert s 2016-09-03T02:33:59.343

@Alberts Yes, you transform just the data element. However, the follow up question doesn't contain any P2SH outputs. It has a multisig output that could be stated as a P2SH output, but no P2SH outputs.Nick ODell 2016-09-03T04:41:23.927

I think you are looking at the address that signed for the transaction, When i follow your instructions i get the address that signed for this output. I was interested in the P2SH address (3...), how to extract it from a redeem script. I did figure that out and have posted the answer in the follow up question.Albert s 2016-09-06T23:31:34.350

@Alberts Your extraction is correct for bare multisig outputs. However, people also use P2SH, and your code will not work correctly for that. What's the difference? P2SH has an output script like OP_HASH160 &lt;hash&gt; OP_EQUAL and bare multisig looks like &lt;something&gt; OP_CHECKMULTISIGVERIFYNick ODell 2016-09-06T23:39:36.407

@Alberts To get a sense of what I'm talking about, try your code on this transaction: https://blockchain.info/tx/721df255f1f2b58e30bf1f4859664189202ef58b60c269e385651eb2ac7a781d

Nick ODell 2016-09-06T23:40:46.997