Skip to content
Verified contractExactBUSL-1.1

BTCUtils

Address0xcc01ab1d608f26fe1a0d226ebd6ab3d7f5cebabe
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,399,864
Creation transaction
0xd6437f19f4…2f6cf44a58

src/protocol/lib/helpers/BTCUtils.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import "./OpCodes.sol";
import {CompactSize} from "./CompactSize.sol";

/**
 * @title BTCUtils
 * @notice This library contains functionality to make easier to work with Bitcoin transactions in Solidity.
 * @notice This library is based in this document:
 *   https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format
 */
library BTCUtils {
    uint256 private constant HASH160_SIZE = 20;
    uint256 private constant SHA256_SIZE = 32;
    uint256 private constant TAPROOT_PUBKEY_SIZE = 32;

    uint8 private constant OUTPOINT_SIZE = 36;
    uint8 private constant OUTPUT_VALUE_SIZE = 8;

    uint8 private constant PUBKEY_HASH_START = 3;
    bytes1 private constant PUBKEY_HASH_MAINNET_BYTE = 0x00;
    bytes1 private constant PUBKEY_HASH_TESTNET_BYTE = 0x6f;

    uint8 private constant SCRIPT_HASH_START = 2;
    bytes1 private constant SCRIPT_HASH_MAINNET_BYTE = 0x05;
    bytes1 private constant SCRIPT_HASH_TESTNET_BYTE = 0xc4;

    uint256 private constant BECH32_WORD_SIZE = 5;
    uint256 private constant BYTE_SIZE = 8;

    bytes1 private constant WITNESS_VERSION_0 = 0x00;
    bytes1 private constant WITNESS_VERSION_1 = 0x01;

    /**
     * @notice This struct contains the information of a tx output separated by fields
     * @notice Its just to have a structured representation of the output
     *
     */
    struct TxRawOutput {
        uint64 value;
        bytes pkScript;
        uint256 scriptSize;
        uint256 totalSize;
    }

    function version() external pure returns (string memory) {
        return "0.2.1";
    }

    /// @notice Read the number of inputs declared by a raw transaction
    /// @param rawTx the raw transaction
    /// @return The input count decoded from the transaction's CompactSize input counter
    /// @dev Reads only the version, the optional SegWit marker/flag and the counter, so the cost is
    ///      independent of the input count. Callers that must bound a caller-supplied transaction use
    ///      this instead of `getOutputs`, whose per-input walk is the work being bounded. The length
    ///      guard covers unvalidated calldata, where a transaction too short to hold the marker would
    ///      otherwise panic on the index rather than report `BufferTooShort`. It admits every length
    ///      that can hold both marker bytes, so this function and `getOutputs` always agree on whether
    ///      a given transaction is SegWit.
    function getInputCount(bytes calldata rawTx) public pure returns (uint64) {
        uint256 currentPosition = 4;

        if (rawTx.length >= 6 && rawTx[4] == 0x00 && rawTx[5] == 0x01) {
            // if its segwit, skip marker and flag
            currentPosition = 6;
        }

        uint64 inputCount;
        (inputCount,) = CompactSize.decodeCalldata(rawTx, currentPosition);
        return inputCount;
    }

    /// @notice Parse a raw transaction to get an array of its outputs in a structured representation
    /// @param rawTx the raw transaction
    /// @return An array of `TxRawOutput` with the outputs of the transaction
    function getOutputs(bytes calldata rawTx) public pure returns (TxRawOutput[] memory) {
        uint256 currentPosition = 4;

        if (rawTx[4] == 0x00 && rawTx[5] == 0x01) {
            // if its segwit, skip marker and flag
            currentPosition = 6;
        }

        uint64 inputCount;
        (inputCount, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);

        uint64 scriptLarge;
        for (uint64 i = 0; i < inputCount; i++) {
            currentPosition += OUTPOINT_SIZE;
            (scriptLarge, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);
            currentPosition += scriptLarge + 4;
        }

        uint64 outputCount;
        (outputCount, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);

        TxRawOutput[] memory result = new TxRawOutput[](outputCount);
        for (uint256 i = 0; i < outputCount; i++) {
            result[i] = extractRawOutput(currentPosition, rawTx);
            currentPosition += result[i].totalSize;
        }
        return result;
    }

    function extractRawOutput(uint256 position, bytes calldata rawTx) private pure returns (TxRawOutput memory) {
        uint256 startPosition = position;
        TxRawOutput memory result = TxRawOutput(0, "", 0, 0);
        result.value = CompactSize.readUint64LECalldata(rawTx, position);
        position += OUTPUT_VALUE_SIZE;

        uint64 scriptLength;
        (scriptLength, position) = CompactSize.decodeCalldata(rawTx, position);

        result.pkScript = rawTx[position:position + scriptLength];
        result.scriptSize = scriptLength;
        result.totalSize = position + scriptLength - startPosition;
        return result;
    }

    /// @notice Parse a raw output script whose type is not known by the consumer. The function will
    /// return the corresponding address if the type of the script is supported or an error if not.
    /// For the addresses that are encoded with base58check the checksum bytes are not included in
    /// the resulting byte array
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @param mainnet if the address to generate is from mainnet or testnet
    /// @return The address bytes regarless of the output script type
    function outputScriptToAddress(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
        if (isP2PKHOutput(outputScript)) {
            return parsePayToPubKeyHash(outputScript, mainnet);
        }
        if (isP2SHOutput(outputScript)) {
            return parsePayToScriptHash(outputScript, mainnet);
        }
        if (isP2WPKHOutput(outputScript)) {
            return parsePayToWitnessPubKeyHash(outputScript);
        }
        if (isP2WSHOutput(outputScript)) {
            return parsePayToWitnessScriptHash(outputScript);
        }
        if (isP2TROutput(outputScript)) {
            return parsePayToTaproot(outputScript);
        }
        revert("Unsupported script type");
    }

    /// @notice Check if a raw output script is a pay-to-public-key-hash output
    /// @param pkScript the fragment of the raw transaction containing the raw output script
    /// @return Whether the script has a pay-to-public-key-hash output structure or not
    function isP2PKHOutput(bytes memory pkScript) public pure returns (bool) {
        return pkScript.length == 25
            && bytes25(pkScript) & 0xFFFFFF0000000000000000000000000000000000000000FFFF
                == 0x76A914000000000000000000000000000000000000000088AC;
    }

    /// @notice Check if a raw output script is a pay-to-script-hash output
    /// @param pkScript the fragment of the raw transaction containing the raw output script
    /// @return Whether the script has a pay-to-script-hash output structure or not
    function isP2SHOutput(bytes memory pkScript) public pure returns (bool) {
        return pkScript.length == 23
            && bytes23(pkScript) & 0xFFFF0000000000000000000000000000000000000000FF
                == 0xA914000000000000000000000000000000000000000087;
    }

    /// @notice Check if a raw output script is a pay-to-witness-pubkey-hash output
    /// @param pkScript the fragment of the raw transaction containing the raw output script
    /// @return Whether the script has a pay-to-witness-pubkey-hash output structure or not
    function isP2WPKHOutput(bytes memory pkScript) public pure returns (bool) {
        return pkScript.length == 22 && bytes2(pkScript) == 0x0014;
    }

    /// @notice Check if a raw output script is a pay-to-witness-script-hash output
    /// @param pkScript the fragment of the raw transaction containing the raw output script
    /// @return Whether the script has a pay-to-witness-script-hash output structure or not
    function isP2WSHOutput(bytes memory pkScript) public pure returns (bool) {
        return pkScript.length == 34 && bytes2(pkScript) == 0x0020;
    }

    /// @notice Check if a raw output script is a pay-to-taproot output
    /// @notice Reference for implementation: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
    /// @param pkScript the fragment of the raw transaction containing the raw output script
    /// @return Whether the script has a pay-to-taproot output structure or not
    function isP2TROutput(bytes memory pkScript) public pure returns (bool) {
        return pkScript.length == 34 && bytes2(pkScript) == 0x5120;
    }

    /// @notice Parse a raw pay-to-public-key-hash output script to get the corresponding address,
    /// the resulting byte array doesn't include the checksum bytes of the base58check encoding at
    /// the end
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @param mainnet if the address to generate is from mainnet or testnet
    /// @return The address generated using the receiver's public key hash
    function parsePayToPubKeyHash(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
        require(isP2PKHOutput(outputScript), "Script hasn't the required structure");

        bytes memory destinationAddress = new bytes(HASH160_SIZE + 1);
        for (uint256 i = PUBKEY_HASH_START; i < HASH160_SIZE + PUBKEY_HASH_START; i++) {
            destinationAddress[i - PUBKEY_HASH_START + 1] = outputScript[i];
        }

        destinationAddress[0] = mainnet ? PUBKEY_HASH_MAINNET_BYTE : PUBKEY_HASH_TESTNET_BYTE;
        return destinationAddress;
    }

    /// @notice Parse a raw pay-to-script-hash output script to get the corresponding address,
    /// the resulting byte array doesn't include the checksum bytes of the base58check encoding at
    /// the end
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @param mainnet if the address to generate is from mainnet or testnet
    /// @return The address generated using the script hash
    function parsePayToScriptHash(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
        require(isP2SHOutput(outputScript), "Script hasn't the required structure");

        bytes memory destinationAddress = new bytes(HASH160_SIZE + 1);
        for (uint256 i = SCRIPT_HASH_START; i < HASH160_SIZE + SCRIPT_HASH_START; i++) {
            destinationAddress[i - SCRIPT_HASH_START + 1] = outputScript[i];
        }

        destinationAddress[0] = mainnet ? SCRIPT_HASH_MAINNET_BYTE : SCRIPT_HASH_TESTNET_BYTE;
        return destinationAddress;
    }

    /// @notice Parse a raw pay-to-witness-pubkey-hash output script to get the corresponding address words,
    /// the resulting words are only the data part of the bech32 encoding and doesn't include the HRP
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @return The address bech32 words generated using the pubkey hash
    function parsePayToWitnessPubKeyHash(bytes calldata outputScript) public pure returns (bytes memory) {
        require(isP2WPKHOutput(outputScript), "Script hasn't the required structure");
        uint256 length = 1 + total5BitWords(HASH160_SIZE);
        bytes memory result = new bytes(length);
        result[0] = WITNESS_VERSION_0;
        bytes memory words = to5BitWords(outputScript[2:]);
        for (uint256 i = 1; i < length; i++) {
            result[i] = words[i - 1];
        }
        return result;
    }

    /// @notice Parse a raw pay-to-witness-script-hash output script to get the corresponding address words,
    /// the resulting words are only the data part of the bech32 encoding and doesn't include the HRP
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @return The address bech32 words generated using the script hash
    function parsePayToWitnessScriptHash(bytes calldata outputScript) public pure returns (bytes memory) {
        require(isP2WSHOutput(outputScript), "Script hasn't the required structure");
        uint256 length = 1 + total5BitWords(SHA256_SIZE);
        bytes memory result = new bytes(length);
        result[0] = WITNESS_VERSION_0;
        bytes memory words = to5BitWords(outputScript[2:]);
        for (uint256 i = 1; i < length; i++) {
            result[i] = words[i - 1];
        }
        return result;
    }

    /// @notice Parse a raw pay-to-taproot output script to get the corresponding address words,
    /// the resulting words are only the data part of the bech32m encoding and doesn't include the HRP
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @return The address bech32m words generated using the taproot pubkey hash
    function parsePayToTaproot(bytes calldata outputScript) public pure returns (bytes memory) {
        require(isP2TROutput(outputScript), "Script hasn't the required structure");
        uint256 length = 1 + total5BitWords(TAPROOT_PUBKEY_SIZE);
        bytes memory result = new bytes(length);
        result[0] = WITNESS_VERSION_1;
        bytes memory words = to5BitWords(outputScript[2:]);
        for (uint256 i = 1; i < length; i++) {
            result[i] = words[i - 1];
        }
        return result;
    }

    /// @notice Parse a raw null-data output script to get its content
    /// @param outputScript the fragment of the raw transaction containing the raw output script
    /// @return The content embedded inside the script
    function parseNullDataScript(bytes calldata outputScript) public pure returns (bytes memory) {
        require(outputScript.length > 1, "Invalid size");
        require(outputScript[0] == OpCodes.OP_RETURN, "Not OP_RETURN");
        return outputScript[1:];
    }

    /// @notice Hash a bitcoin raw transaction to get its txid (reversed double sha256)
    /// @param btcTx the transaction to hash (supports both legacy and segwit serialization)
    /// @return The transaction id (txid), NOT the witness txid (wtxid)
    /// @dev For segwit transactions, strips the marker, flag, and witness data before hashing
    ///      to compute the correct txid per BIP-141
    function hashBtcTx(bytes calldata btcTx) public pure returns (bytes32) {
        bytes memory toHash;

        // Detect segwit serialization: marker=0x00 flag=0x01 at bytes[4:6]
        if (btcTx.length > 6 && btcTx[4] == 0x00 && btcTx[5] == 0x01) {
            toHash = _stripWitnessData(btcTx);
        } else {
            toHash = btcTx;
        }

        return _reverseBytes32(sha256(abi.encodePacked(sha256(toHash))));
    }

    /// @dev Reverse the byte order of a 32-byte word in a single pass via masked
    ///      shifts. Swap adjacent 1, 2, 4, 8, and 16-byte groups (O(log n)).
    function _reverseBytes32(bytes32 v) private pure returns (bytes32) {
        v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8)
            | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
        v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16)
            | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
        v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32)
            | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
        v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64)
            | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
        return (v >> 128) | (v << 128);
    }

    /// @notice Strip witness data from a segwit transaction to produce non-witness serialization
    /// @param btcTx Segwit-serialized transaction (must have marker=0x00, flag=0x01 at bytes[4:6])
    /// @return Non-witness serialization: version | inputs | outputs | locktime
    /// @dev Per BIP-141, txid is computed from non-witness serialization
    function _stripWitnessData(bytes calldata btcTx) private pure returns (bytes memory) {
        // Parse past inputs and outputs to find where witness data begins
        uint256 pos = 6; // skip version(4) + marker(1) + flag(1)

        // Parse inputs
        uint64 inputCount;
        (inputCount, pos) = CompactSize.decodeCalldata(btcTx, pos);
        for (uint64 i = 0; i < inputCount; i++) {
            pos += OUTPOINT_SIZE; // prevout (txid + vout)
            uint64 scriptLen;
            (scriptLen, pos) = CompactSize.decodeCalldata(btcTx, pos);
            pos += scriptLen + 4; // scriptSig + sequence
        }

        // Parse outputs
        uint64 outputCount;
        (outputCount, pos) = CompactSize.decodeCalldata(btcTx, pos);
        for (uint64 i = 0; i < outputCount; i++) {
            pos += OUTPUT_VALUE_SIZE; // value
            uint64 scriptLen;
            (scriptLen, pos) = CompactSize.decodeCalldata(btcTx, pos);
            pos += scriptLen; // scriptPubKey
        }

        // pos now points to start of witness data; locktime is last 4 bytes.
        // Reject txs where witness+locktime don't fit after the parsed body,
        // otherwise btcTx[6:pos] and btcTx[length-4:] overlap and the last 4
        // bytes of the body get reused as locktime, producing a wrong txid.
        if (pos + 4 > btcTx.length) revert CompactSize.BufferTooShort(pos, pos + 4, btcTx.length);

        // Construct: version(4) + inputs_and_outputs(btcTx[6:pos]) + locktime(4)
        return abi.encodePacked(btcTx[:4], btcTx[6:pos], btcTx[btcTx.length - 4:]);
    }

    /// @dev Gets the timestamp of a Bitcoin block header
    /// @param header The block header
    /// @return The timestamp of the block header
    function getBtcBlockTimestamp(bytes memory header) public pure returns (uint256) {
        // bitcoin header is 80 bytes and timestamp is 4 bytes from byte 68 to byte 71 (both inclusive)
        require(header.length == 80, "Invalid header length");

        return sliceUint32FromLSB(header, 68);
    }

    // bytes must have at least 28 bytes before the uint32
    function sliceUint32FromLSB(bytes memory bs, uint256 offset) private pure returns (uint32) {
        require(bs.length >= offset + 4, "Slicing out of range");

        return uint32(uint8(bs[offset])) | (uint32(uint8(bs[offset + 1])) << 8) | (uint32(uint8(bs[offset + 2])) << 16)
            | (uint32(uint8(bs[offset + 3])) << 24);
    }

    /// @notice Referece for implementation: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
    function to5BitWords(bytes memory byteArray) private pure returns (bytes memory) {
        uint8 MAX_VALUE = 31;

        uint256 currentValue = 0;
        uint256 bitCount = 0;
        uint8 resultIndex = 0;
        bytes memory result = new bytes(total5BitWords(byteArray.length));

        for (uint256 i = 0; i < byteArray.length; ++i) {
            currentValue = (currentValue << BYTE_SIZE) | uint8(byteArray[i]);
            bitCount += BYTE_SIZE;
            while (bitCount >= BECH32_WORD_SIZE) {
                bitCount -= BECH32_WORD_SIZE;
                // this mask ensures that the result will always have 5 bits
                result[resultIndex] = bytes1(uint8((currentValue >> bitCount) & MAX_VALUE));
                resultIndex++;
            }
        }

        if (bitCount > 0) {
            result[resultIndex] = bytes1(uint8((currentValue << (BECH32_WORD_SIZE - bitCount)) & MAX_VALUE));
        }
        return result;
    }

    function total5BitWords(uint256 numberOfBytes) private pure returns (uint256) {
        uint256 total = (numberOfBytes * BYTE_SIZE) / BECH32_WORD_SIZE;
        bool extraWord = (numberOfBytes * BYTE_SIZE) % BECH32_WORD_SIZE == 0;
        return total + (extraWord ? 0 : 1);
    }
}

src/protocol/lib/helpers/CompactSize.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title CompactSize
 * @notice Bitcoin CompactSize integer encoding/decoding utilities
 * @dev Implements Bitcoin's variable-length integer format used in transaction serialization
 * @dev Reference: https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
 */
library CompactSize {
    error InvalidCompactSize(uint256 offset, uint8 prefix, uint64 value, uint64 minValue);
    error BufferTooShort(uint256 offset, uint256 requiredLength, uint256 availableLength);

    // ============ Encoding Functions ============

    /**
     * @notice Encode an integer as Bitcoin CompactSize format
     * @param value The integer to encode (uint64)
     * @return Encoded bytes in CompactSize format
     * @dev Format:
     *      - value < 0xFD: [value] (1 byte)
     *      - value <= 0xFFFF: [0xFD][value as LE uint16] (3 bytes)
     *      - value <= 0xFFFFFFFF: [0xFE][value as LE uint32] (5 bytes)
     *      - value > 0xFFFFFFFF: [0xFF][value as LE uint64] (9 bytes)
     */
    function encode(uint64 value) internal pure returns (bytes memory) {
        if (value < 0xFD) {
            // Single byte
            return abi.encodePacked(uint8(value));
        } else if (value <= 0xFFFF) {
            // 0xFD + 2 bytes (little-endian uint16)
            return abi.encodePacked(uint8(0xFD), uint8(value), uint8((value >> 8)));
        } else if (value <= 0xFFFFFFFF) {
            // 0xFE + 4 bytes (little-endian uint32)
            return abi.encodePacked(
                uint8(0xFE), uint8(value), uint8((value >> 8)), uint8((value >> 16)), uint8((value >> 24))
            );
        } else {
            // 0xFF + 8 bytes (little-endian uint64)
            return abi.encodePacked(
                uint8(0xFF),
                uint8(value),
                uint8((value >> 8)),
                uint8((value >> 16)),
                uint8((value >> 24)),
                uint8((value >> 32)),
                uint8((value >> 40)),
                uint8((value >> 48)),
                uint8((value >> 56))
            );
        }
    }

    /**
     * @notice Get the encoded length for a given value
     * @param value The value to measure
     * @return Length in bytes of the CompactSize encoding
     */
    function encodedLength(uint64 value) internal pure returns (uint8) {
        if (value < 0xFD) return 1;
        if (value <= 0xFFFF) return 3;
        if (value <= 0xFFFFFFFF) return 5;
        return 9;
    }

    // ============ Decoding Functions ============

    /**
     * @notice Decode CompactSize integer from bytes
     * @param data The bytes to decode from
     * @param offset Starting position in the data
     * @return value The decoded uint64 value
     * @return newOffset Position immediately after the decoded CompactSize
     * @dev Reverts if data is malformed or insufficient
     */
    function decode(bytes memory data, uint256 offset) internal pure returns (uint64 value, uint256 newOffset) {
        if (offset >= data.length) revert BufferTooShort(offset, offset + 1, data.length);

        uint8 firstByte = uint8(data[offset]);

        if (firstByte < 0xFD) {
            // Single byte value
            return (uint64(firstByte), offset + 1);
        } else if (firstByte == 0xFD) {
            // 2-byte value (uint16)
            if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
            value = readUint16LE(data, offset + 1);
            if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD); // Non-canonical encoding
            return (value, offset + 3);
        } else if (firstByte == 0xFE) {
            // 4-byte value (uint32)
            if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
            value = readUint32LE(data, offset + 1);
            if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000); // Non-canonical encoding
            return (value, offset + 5);
        } else {
            // 8-byte value (uint64)
            if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
            value = readUint64LE(data, offset + 1);
            if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000); // Non-canonical encoding
            return (value, offset + 9);
        }
    }

    /**
     * @notice Decode CompactSize from calldata
     * @param data The calldata to decode from
     * @param offset Starting position
     * @return value The decoded uint64 value
     * @return newOffset Position immediately after the decoded CompactSize
     */
    function decodeCalldata(bytes calldata data, uint256 offset)
        internal
        pure
        returns (uint64 value, uint256 newOffset)
    {
        if (offset >= data.length) {
            revert BufferTooShort(offset, offset + 1, data.length);
        }

        uint8 firstByte = uint8(data[offset]);

        if (firstByte < 0xFD) {
            return (uint64(firstByte), offset + 1);
        } else if (firstByte == 0xFD) {
            if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
            value = readUint16LECalldata(data, offset + 1);
            if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD);
            return (value, offset + 3);
        } else if (firstByte == 0xFE) {
            if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
            value = readUint32LECalldata(data, offset + 1);
            if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000);
            return (value, offset + 5);
        } else {
            if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
            value = readUint64LECalldata(data, offset + 1);
            if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000);
            return (value, offset + 9);
        }
    }

    // ============ Little-Endian Reading Helpers ============

    /**
     * @notice Read little-endian uint16 from bytes
     */
    function readUint16LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
    }

    /**
     * @notice Read little-endian uint32 from bytes
     */
    function readUint32LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
    }

    /**
     * @notice Read little-endian uint64 from bytes
     */
    function readUint64LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
            | (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
            | (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
    }

    /**
     * @notice Read little-endian uint16 from calldata
     */
    function readUint16LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
    }

    /**
     * @notice Read little-endian uint32 from calldata
     */
    function readUint32LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
    }

    /**
     * @notice Read little-endian uint64 from calldata
     */
    function readUint64LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
            | (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
            | (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
    }
}

src/protocol/lib/helpers/OpCodes.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

library OpCodes {
    // Basic opcodes
    bytes1 internal constant OP_0 = 0x00;
    bytes1 internal constant OP_1 = 0x51;

    // Stack manipulation
    bytes1 internal constant OP_DUP = 0x76;
    bytes1 internal constant OP_DROP = 0x75;

    // Crypto operations
    bytes1 internal constant OP_HASH160 = 0xa9;
    bytes1 internal constant OP_CHECKSIG = 0xac;
    bytes1 internal constant OP_CHECKSIGVERIFY = 0xad;
    bytes1 internal constant OP_CHECKSIGADD = 0xba; // BIP342 Tapscript

    // Comparison
    bytes1 internal constant OP_EQUAL = 0x87;
    bytes1 internal constant OP_EQUALVERIFY = 0x88;

    // Numeric operations
    bytes1 internal constant OP_NUMEQUAL = 0x9c;
    bytes1 internal constant OP_NUMEQUALVERIFY = 0x9d;

    // Flow control
    bytes1 internal constant OP_IF = 0x63;
    bytes1 internal constant OP_ELSE = 0x67;
    bytes1 internal constant OP_ENDIF = 0x68;
    bytes1 internal constant OP_RETURN = 0x6a;

    // Locktime
    bytes1 internal constant OP_CHECKSEQUENCEVERIFY = 0xb2;

    // Push data opcodes
    bytes1 internal constant PUSH_20 = 0x14; // 20 bytes
    bytes1 internal constant PUSH_32 = 0x20; // 32 bytes

    // Push data with length prefix
    bytes1 internal constant OP_PUSHDATA1 = 0x4c; // Next byte contains length
    bytes1 internal constant OP_PUSHDATA2 = 0x4d; // Next 2 bytes contain length
    bytes1 internal constant OP_PUSHDATA4 = 0x4e; // Next 4 bytes contain length
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    ":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":aave-v4/=lib/aave-v4/src/",
    ":elliptic-curve-solidity/=lib/elliptic-curve-solidity/",
    ":erc4626-tests/=lib/aave-v4/lib/erc4626-tests/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    ":src/access/=lib/aave-v4/src/access/",
    ":src/config-engine/=lib/aave-v4/src/config-engine/",
    ":src/dependencies/=lib/aave-v4/src/dependencies/",
    ":src/deployments/=lib/aave-v4/src/deployments/",
    ":src/hub/=lib/aave-v4/src/hub/",
    ":src/interfaces/IExtSload.sol=lib/aave-v4/src/interfaces/IExtSload.sol",
    ":src/interfaces/IIntentConsumer.sol=lib/aave-v4/src/interfaces/IIntentConsumer.sol",
    ":src/interfaces/IMulticall.sol=lib/aave-v4/src/interfaces/IMulticall.sol",
    ":src/interfaces/INoncesKeyed.sol=lib/aave-v4/src/interfaces/INoncesKeyed.sol",
    ":src/interfaces/IRescuable.sol=lib/aave-v4/src/interfaces/IRescuable.sol",
    ":src/libraries/=lib/aave-v4/src/libraries/",
    ":src/position-manager/=lib/aave-v4/src/position-manager/",
    ":src/spoke/=lib/aave-v4/src/spoke/",
    ":src/utils/=lib/aave-v4/src/utils/",
    ":vault-contracts/=src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.