This article explains how to create Bitcoin script based on first article from series and get corresponding P2SH address.
Just to mention, a simplest script is math equation 5 + 9 = 14. This equation will be used to create Bitcoin script and Bitcoin P2SH address later. All computations will be performed on Bitcoin testnet to avoid any looses of useful costs.
Making a script.
Our script is: “OP_PUSH 14 OP_PUSH 5 OP_PUSH 9 OP_ADD OP_EQUAL”
But now we have to decide what part of script will be in scriptPubKey and what — in scriptSig. Let’s put “OP_PUSH 14” to scriptSig and rest of script to scriptPubKey.
As was specified in previous article Bitcoin uses commands (or opcodes) which are predefined. But we can’t write down opcode’s names as they are and write something like “Bitcoin make me a sandwich”. We should write script in terms of Bitcoin script specification and use special HEX opcode numbers instead of names (e.g. 93 instead of OP_ADD).
So, let’s take scriptPubKey part of our whole script and convert it from opcode’s names format to opcode’s numbers format. All HEX numbers of opcodes we can get here.
Used opcodes:
OP_5 (OP_PUSH 5) = 55
OP_9 (OP_PUSH 9) = 59
OP_ADD = 93
OP_EQUAL = 87
Source: OP_PUSH 5 OP_PUSH 9 OP_ADD OP_EQUAL
Converted (HEX): 55599387
We’ve got our scriptPubKey in HEX format. And now we can make P2SH address for this script.
Deriving P2SH address from the script.
To make P2SH address we should take our script and perform some calculations on it:
- Get SHA-256 hash from the sctipt. Let’s use this calculator for our purposes. Type scriptPubKey HEX into “Binary hash” field, hash it and look for sha-256 in result. It should be 85bb3e8431b7cd8f9b71e823914c8c317073870427d8f4aa309ec6a35f5ad3a0.
- Get RipeMD160 (or hash160). Put previously obtained SHA-256 hash into “Binary hash” and hash it again. Find RipeMD160 field int the result. It should be 87f3b621f18c50068b7daba160bb2c51fdd6a5e2.
- Attach P2SH address version in front of hash160. For Bitcoin testnet it is “c4”. And the result should be c487f3b621f18c50068b7daba160bb2c51fdd6a5e2
- Double SHA-256 hash of hash160 with address version. Final hash should be 17284052d8c21bc45cf0ae969b75fea01d15c22a2e507874776062462e3ed3d1.
- Get first 4 bytes (8 characters) of double SHA-256 hash and attach it to end of hash160 hash with address version. Hash with checksum should be c487f3b621f18c50068b7daba160bb2c51fdd6a5e217284052.
- Encode hash from item 5 with BASE58. Use this tool for it.
After performing all 6 items we should get our address:
2N5e5AYqvwxPFSKEm5mXm8AfN3DaqiBQpiM
That’s it, we have P2SH address and we can now send coins to this address and spend them by creating transaction with right scriptSig value.
Continue read in next article.