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: 5221031e71524a170c87855f7e9bd3b212a0a3e28e3c91c19f24a9a0d9e251e5ffe1321031e71524a170c87855f7e9bd3b212a0a3e28e3c91c19f24a9a0d9e251e5ffe1352ae

Expected results:

  • P2SH Address: 3PRx8wvqghQB1S8xGpFBmcVjN5fxGvpjLE
  • ASM: OP_2 031e71524a170c87855f7e9bd3b212a0a3e28e3c91c19f24a9a0d9e251e5ffe13 031e71524a170c87855f7e9bd3b212a0a3e28e3c91c19f24a9a0d9e251e5ffe13 OP_2 OP_CHECKMULTISIG

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

Solution code