Implement OP_ADD, OP_HASH160

In Bitcoin script, OP_ADD adds the top two items on the stack, while OP_HASH160 computes the RIPEMD160(SHA256(x)) hash of the top stack item.

Task

Complete the OP_ADD and OP_HASH160 functions in challenges/OpcodeFunctions.js:

  1. Implement OP_ADD to add the top two stack items, handling Bitcoin's number encoding.
  2. Implement OP_HASH160 to compute the RIPEMD160(SHA256(x)) hash of the top stack item.

Implementation

P2PK ScriptPubKey Decoder Exercise
import CryptoJS from 'crypto-js';

export function encodeNum(num) {
    if (num === 0) return Buffer.alloc(0);

    const absNum = Math.abs(num);
    const negative = num < 0;
    const result = [];
    let currentNum = absNum;

    while (currentNum) {
        result.push(currentNum & 0xff);
        currentNum >>>= 8;
    }

    if (result[result.length - 1] & 0x80) {
        if (negative) {
            result.push(0x80);
        } else {
            result.push(0);
        }
    } else if (negative) {
        result[result.length - 1] |= 0x80;
    }

    return Buffer.from(result);

}

export function decodeNum(buffer) {
    if (buffer.length === 0) return 0;

    const bigEndian = Buffer.from(buffer).reverse();
    let result = 0;
    const negative = bigEndian[0] & 0x80;

    if (negative) {
        result = bigEndian[0] & 0x7f;
    } else {
        result = bigEndian[0];
    }

    for (let i = 1; i < bigEndian.length; i++) {
        result <<= 8;
        result += bigEndian[i];
    }

    if (negative) {
        return -result;
    } else {
        return result;
    }

}

export const OP_ADD = (stack) => {
    // TODO: Implement OP_ADD
}

export const OP_HASH160 = (stack) => {
    // TODO: Implement OP_HASH160
}

export const OP_CODE_FUNCTIONS = {
    OP_ADD,
    OP_HASH160
    // Add more opcodes here
}

Ready to Code?

Choose your preferred language to begin

Hints

Click to reveal next hint (0/4)
  • Use the provided encodeNum and decodeNum functions for OP_ADD
  • For OP_HASH160, use CryptoJS.SHA256 and CryptoJS.RIPEMD160
  • Remember to handle edge cases like insufficient stack items
  • The stack contains Buffer objects, not plain numbers

Solution

Solution Code

Test your implementation using the Bitcoin Opcode Simulator above. Try various inputs to ensure your opcodes handle different scenarios correctly.