Implement Script Parser

Bitcoin uses a stack-based scripting language to validate transactions. Understanding how to parse and interpret these scripts is crucial for working with Bitcoin transactions.

Task

Complete the parseScript function in challenges/ScriptParser.js:

  1. Implement a function that takes a hexadecimal string representing a Bitcoin script and returns an array of parsed operations and data pushes.
  2. The function should handle various opcodes and data push operations, including OP_PUSHDATA1, OP_PUSHDATA2, and OP_PUSHDATA4.
  3. For each script element, return an object with type (either 'opcode' or 'data') and value (the opcode name or the data in hexadecimal).

Implementation

P2PK ScriptPubKey Decoder Exercise
import { OpCode } from './OpCodes';

export function parseScript(scriptHex) {
  const script = Buffer.from(scriptHex.replace(/^0x/, ''), 'hex');
  const parsedScript = [];
  let offset = 0;

while (offset < script.length) {
// TODO: Implement script parsing logic
// 1. Read the current byte
// 2. Determine if it's an opcode or data push
// 3. Handle data pushes (including OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4)
// 4. Add the parsed element to the parsedScript array
// 5. Update the offset
}

return parsedScript;
}

Ready to Code?

Choose your preferred language to begin

Hints

Click to reveal next hint (0/5)
  • Use a while loop to iterate through the script buffer
  • Handle data push operations for opcodes 0x01 to 0x4b
  • Implement special cases for OP_PUSHDATA1, OP_PUSHDATA2, and OP_PUSHDATA4
  • Use the OpCode and OP_CODE_NAMES objects for opcode lookup
  • Remember to handle edge cases and potential errors

Solution

Solution Code

Test your implementation using the Bitcoin Script Parser Simulator above. Try various script hexadecimal inputs to ensure your parser handles different scenarios correctly.