Exercise 2: Hard

Creating a P2SH Address in bitcoin

In this exercise, you'll implement the core functionality to create a Pay-to-Script-Hash (P2SH) address in bitcoin.

Exercise Instructions

Your task is to implement the generateP2SHAddress and hexToASM functions in the bitcoinUtils.js file.

  1. Implement generateP2SHAddress as described in the previous instructions.
  2. Implement hexToASM to convert the hex redeem script to its ASM representation:
    • Parse the hex script byte by byte.
    • Convert known opcodes to their string representations (e.g., '51' to 'OP_1').
    • For push data operations, extract the correct number of bytes as a hex string.
    • Join the parsed elements with spaces.

Test your implementation with this redeem script: 5121022afc20bf379bc96a2f4e9e63ffceb8652b2b6a097f63fbee6ecec2a49a48010e2103a767c7221e9f15f870f1ad9311f5ab937d79fcaeee15bb2c722bca515581b4c052ae

Expected results:

  • P2SH Address: 3QwJXQQu82a9jErSkTJxX3a1TABmvCqbae
  • ASM: OP_1 OP_PUSHBYTES_33 022afc20bf379bc96a2f4e9e63ffceb8652b2b6a097f63fbee6ecec2a49a48010e OP_PUSHBYTES_33 03a767c7221e9f15f870f1ad9311f5ab937d79fcaeee15bb2c722bca515581b4c0 OP_2 OP_CHECKMULTISIG

This script represents a 2-of-2 multisig P2SH address.

Solution code

Suggest Edits