Start your career in bitcoin open source — ₿OSS

APPLY TODAY

Exercise 2: Hard

P2PKH ScriptPubKey to ASM Converter

In this exercise, you'll implement a function to convert a P2PK (Pay-to-Public-Key) ScriptPubKey from its hexadecimal representation to ASM format.

  1. Implement the decodeP2PKHScriptPubKey function in the code editor below.
  2. The function should convert the input hex string to a Buffer.
  3. Verify that the script starts with OP_DUP (0x76) and OP_HASH160 (0xA9).
  4. Extract the public key hash (20 bytes).
  5. Verify that the script ends with OP_EQUALVERIFY (0x88) and OP_CHECKSIG (0xAC).
  6. Construct and return the ASM string: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
P2PK ScriptPubKey Decoder Exercise
// Simplified OPS object for this exercise
const OPS = {
  OP_DUP: 118,        // 0x76 in decimal
  OP_HASH160: 169,    // 0xA9 in decimal
  OP_EQUALVERIFY: 136, // 0x88 in decimal
  OP_CHECKSIG: 172,   // 0xAC in decimal
};

const REVERSE_OPS = {
118: 'OP_DUP',
169: 'OP_HASH160',
136: 'OP_EQUALVERIFY',
172: 'OP_CHECKSIG',
};

export function decodeP2PKHScriptPubKey(hexScript) {
    // TODO: Implement the decodeP2PKHScriptPubKey function
    // 1. Convert the hexScript to a Buffer
    // 2. Verify the script starts with OP_DUP and OP_HASH160
    // 3. Extract the public key hash (20 bytes)
    // 4. Verify the script ends with OP_EQUALVERIFY and OP_CHECKSIG
    // 5. Verify the script length
    // 6. Return the ASM format string
    // Your code here
}
;

Ready to Code?

Choose your preferred language to begin

Click to reveal next hint (0/3)
  • Remember, P2PKH scripts always start with OP_DUP (0x76) and OP_HASH160 (0xA9).
  • The public key hash is always 20 bytes long.
  • Don't forget to check for OP_EQUALVERIFY (0x88) and OP_CHECKSIG (0xAC) at the end!

Solution code

Suggest Edits