Exercise 3: Hard

P2PK 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.

P2PK Problems
  1. Implement the decodeP2PKScriptPubKey function in the code editor below.
  2. The function should convert the input hex string to a Buffer.
  3. Extract the public key (the first byte indicates the length: 0x41 for uncompressed, 0x21 for compressed).
  4. Verify that the last byte is OP_CHECKSIG (0xAC).
  5. Construct and return the ASM string: <public key in hex> OP_CHECKSIG
P2PK ScriptPubKey Decoder Exercise
// Simplified OPS object for this exercise
const OPS = {
  OP_CHECKSIG: 172,  // 0xac in decimal
};

const REVERSE_OPS = {
172: 'OP_CHECKSIG',
};

export function decodeP2PKScriptPubKey(hexScript) {
    // TODO: Implement the decodeP2PKScriptPubKey function
    // 1. Convert the hexScript to a Buffer
    // 2. Extract the length of the public key (first byte)
    // 3. Extract the public key
    // 4. Verify the last byte is 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/4)
  • Start by converting the hexadecimal input to a Buffer using `Buffer.from(hexScript, 'hex')`. This allows you to work with the script as bytes.
  • Remember that the first byte of the script indicates the length of the public key. Use this to extract the public key from the Buffer.
  • The last byte of the script should always be OP_CHECKSIG (0xAC or 172 in decimal). Make sure to verify this.
  • To construct the ASM string, you'll need to convert the public key back to a hexadecimal string and append the OP_CHECKSIG operation. Use `toString('hex')` to convert the public key Buffer to a hex string.

Solution code