Exercise 1: Medium
In this exercise, you'll construct a P2SH (Pay-to-Script-Hash) ScriptPubKey for a given redeem script within a partially constructed transaction.
Here's a breakdown of the partially constructed transaction:
Field | Value |
---|---|
Version | 02000000 |
Input Count | 02 |
Input 1 TXID | 589d75a45b732e3a92da560086568310e33efe5cfb26bcb2685d7ee712af7a3e |
Input 1 VOUT | 00000000 |
Input 1 ScriptSig Size | 6a |
Input 1 ScriptSig | [scriptsig 1] |
Input 1 Sequence | fdffffff |
Input 2 TXID | 2f8ec63af69ea6d35acb217562bef0467b0354a2dad430a71051041e5cfd0499 |
Input 2 VOUT | 01000000 |
Input 2 ScriptSig Size | 6b |
Input 2 ScriptSig | [scriptsig 2] |
Input 2 Sequence | fdffffff |
Output Count | 02 |
Output 1 Amount | 888a0100000000000 |
Output 1 ScriptPubKey Size | 17 |
Output 1 ScriptPubKey | [scriptpubkey] |
Output 2 Amount | 74658b0000000000 |
Output 2 ScriptPubKey | 1976a91468cfed146aced22f422a68015ff8ca180761912a88ac |
Locktime | eff91700 |
The hexadecimal representation of this transaction is:
10200000002589d75a45b732e3a92da560086568310e33efe5cfb26bcb2685d7ee712af7a3e000000006a-[scriptsig 1]-fdffffff2f8ec63af69ea6d35acb217562bef0467b0354a2dad430a71051041e5cfd0499010000006b-[scriptsig 2]-fdffffff02888a01000000000017-[scriptpubkey]-74658b00000000001976a91468cfed146aced22f422a68015ff8ca180761912a88aceff91700
Exercise
Your task is to complete the constructP2SHScriptPubKey
function which creates a P2SH ScriptPubKey for the following redeem script:
2 3 ADD 5 EQUAL
Instructions:
- Implement the
constructP2SHScriptPubKey
function. - The function should take the redeem script as input and return the complete P2SH ScriptPubKey.
- Remember to hash the redeem script and include the necessary opcodes.
- The provided unit test will check if your implementation is correct.
Choose your preferred language below to start coding:
Ready to Code?
Choose your preferred language to begin
For this exercise, we've provided the crypto-js
(JavaScript) and hashlib
(Python) libraries to help with the hashing operations. You should use the relevant library to implement the P2SH ScriptPubKey function.
You can look up the hex characters for each op_code in the Bitcoin Script wiki page.
- Start by encoding the redeem script as bytes.
- Use CryptoJS.SHA256 to hash the redeem script, then use CryptoJS.RIPEMD160 on the result.
- The P2SH script starts with OP_HASH160 (0xa9).
- Push the 20-byte script hash onto the stack (0x14 followed by the hash).
- End the script with OP_EQUAL (0x87).
Solution code
Inspiration
After completing the exercise, you can check out these testnet transactions to see real P2SH ScriptPubKeys in action:
These transactions demonstrate how P2SH ScriptPubKeys are used in actual Bitcoin transactions on the testnet.