Skip to content

Script

ScriptVerificationFlags

Bases: IntFlag

Script verification flags that may be composed with each other.

These flags control which validation rules are enforced during script verification. Multiple flags can be combined using bitwise OR operations.

Source code in pbk/script.py
class ScriptVerificationFlags(IntFlag):
    """Script verification flags that may be composed with each other.

    These flags control which validation rules are enforced during script
    verification. Multiple flags can be combined using bitwise OR operations.
    """

    NONE = 0
    """No verification flags"""

    P2SH = 1 << 0
    """Evaluate P2SH (BIP16) subscripts"""

    DERSIG = 1 << 2
    """Enforce strict DER (BIP66) compliance"""

    NULLDUMMY = 1 << 4
    """Enforce NULLDUMMY (BIP147)"""

    CHECKLOCKTIMEVERIFY = 1 << 9
    """Enable CHECKLOCKTIMEVERIFY (BIP65)"""

    CHECKSEQUENCEVERIFY = 1 << 10
    """Enable CHECKSEQUENCEVERIFY (BIP112)"""

    WITNESS = 1 << 11
    """Enable WITNESS (BIP141)"""

    TAPROOT = 1 << 17
    """Enable TAPROOT (BIPs 341 & 342)"""

    ALL = (
        P2SH
        | DERSIG
        | NULLDUMMY
        | CHECKLOCKTIMEVERIFY
        | CHECKSEQUENCEVERIFY
        | WITNESS
        | TAPROOT
    )
    """All verification flags combined"""

ALL class-attribute instance-attribute

ALL = P2SH | DERSIG | NULLDUMMY | CHECKLOCKTIMEVERIFY | CHECKSEQUENCEVERIFY | WITNESS | TAPROOT

All verification flags combined

CHECKLOCKTIMEVERIFY class-attribute instance-attribute

CHECKLOCKTIMEVERIFY = 1 << 9

Enable CHECKLOCKTIMEVERIFY (BIP65)

CHECKSEQUENCEVERIFY class-attribute instance-attribute

CHECKSEQUENCEVERIFY = 1 << 10

Enable CHECKSEQUENCEVERIFY (BIP112)

DERSIG class-attribute instance-attribute

DERSIG = 1 << 2

Enforce strict DER (BIP66) compliance

NONE class-attribute instance-attribute

NONE = 0

No verification flags

NULLDUMMY class-attribute instance-attribute

NULLDUMMY = 1 << 4

Enforce NULLDUMMY (BIP147)

P2SH class-attribute instance-attribute

P2SH = 1 << 0

Evaluate P2SH (BIP16) subscripts

TAPROOT class-attribute instance-attribute

TAPROOT = 1 << 17

Enable TAPROOT (BIPs 341 & 342)

WITNESS class-attribute instance-attribute

WITNESS = 1 << 11

Enable WITNESS (BIP141)

ScriptVerifyStatus

Bases: IntEnum

Status codes returned by script verification.

These codes indicate the result of script verification, including success, various error conditions, and validation failures.

Source code in pbk/script.py
class ScriptVerifyStatus(IntEnum):
    """Status codes returned by script verification.

    These codes indicate the result of script verification, including
    success, various error conditions, and validation failures.
    """

    OK = 0
    """Verification succeeded"""

    ERROR_INVALID_FLAGS_COMBINATION = 1
    """The flags were combined in an invalid way."""

    ERROR_SPENT_OUTPUTS_REQUIRED = 2
    """The taproot flag was set, so valid spent_outputs have to be provided."""

ERROR_INVALID_FLAGS_COMBINATION class-attribute instance-attribute

ERROR_INVALID_FLAGS_COMBINATION = 1

The flags were combined in an invalid way.

ERROR_SPENT_OUTPUTS_REQUIRED class-attribute instance-attribute

ERROR_SPENT_OUTPUTS_REQUIRED = 2

The taproot flag was set, so valid spent_outputs have to be provided.

OK class-attribute instance-attribute

OK = 0

Verification succeeded

PrecomputedTransactionData

Bases: KernelOpaquePtr

Reusable structure holding precomputed transaction data for verifying multiple inputs of the same transaction.

This avoids recomputing transaction hashes for each input during script verification. Required when verifying taproot inputs.

Source code in pbk/script.py
class PrecomputedTransactionData(KernelOpaquePtr):
    """Reusable structure holding precomputed transaction data for verifying multiple inputs of
    the same transaction.

    This avoids recomputing transaction hashes for each input during script verification.
    Required when verifying taproot inputs.
    """

    _create_fn = k.btck_precomputed_transaction_data_create
    _destroy_fn = k.btck_precomputed_transaction_data_destroy
    _copy_fn = k.btck_precomputed_transaction_data_copy

    def __init__(
        self, tx_to: "Transaction", spent_outputs: list["TransactionOutput"] | None
    ):
        """Create precomputed transaction data for script verification.

        Args:
            tx_to: The transaction to precompute data for.
            spent_outputs: The outputs spent by the transaction. Required for taproot
                verification, can be None for non-taproot verification.
        """
        spent_outputs_array = (
            (ctypes.POINTER(k.btck_TransactionOutput) * len(spent_outputs))(
                *[output._as_parameter_ for output in spent_outputs]
            )
            if spent_outputs
            else None
        )
        spent_outputs_len = len(spent_outputs) if spent_outputs else 0
        super().__init__(tx_to, spent_outputs_array, spent_outputs_len)

__init__

__init__(tx_to: Transaction, spent_outputs: list[TransactionOutput] | None)

Create precomputed transaction data for script verification.

PARAMETER DESCRIPTION
tx_to

The transaction to precompute data for.

TYPE: Transaction

spent_outputs

The outputs spent by the transaction. Required for taproot verification, can be None for non-taproot verification.

TYPE: list[TransactionOutput] | None

Source code in pbk/script.py
def __init__(
    self, tx_to: "Transaction", spent_outputs: list["TransactionOutput"] | None
):
    """Create precomputed transaction data for script verification.

    Args:
        tx_to: The transaction to precompute data for.
        spent_outputs: The outputs spent by the transaction. Required for taproot
            verification, can be None for non-taproot verification.
    """
    spent_outputs_array = (
        (ctypes.POINTER(k.btck_TransactionOutput) * len(spent_outputs))(
            *[output._as_parameter_ for output in spent_outputs]
        )
        if spent_outputs
        else None
    )
    spent_outputs_len = len(spent_outputs) if spent_outputs else 0
    super().__init__(tx_to, spent_outputs_array, spent_outputs_len)

ScriptPubkey

Bases: KernelOpaquePtr

A Bitcoin script defining spending conditions for an output.

Source code in pbk/script.py
class ScriptPubkey(KernelOpaquePtr):
    """A Bitcoin script defining spending conditions for an output."""

    _create_fn = k.btck_script_pubkey_create
    _destroy_fn = k.btck_script_pubkey_destroy
    _copy_fn = k.btck_script_pubkey_copy

    def __init__(self, data: bytes):
        """Create a script pubkey from raw script data.

        Args:
            data: The script pubkey data containing opcodes and operands.

        Raises:
            RuntimeError: If the C constructor fails (propagated from base class).
        """
        super().__init__((ctypes.c_ubyte * len(data))(*data), len(data))

    def __bytes__(self) -> bytes:
        """Serialize the script pubkey to bytes.

        Returns:
            The raw script data.
        """
        writer = ByteWriter()
        return writer.write(k.btck_script_pubkey_to_bytes, self)

    def __repr__(self) -> str:
        """Return a string representation of the script pubkey."""
        hex_str = str(self)
        preview = hex_str[:32] + "..." if len(hex_str) > 32 else hex_str
        return f"<ScriptPubkey len={len(bytes(self))} hex={preview}>"

    def __str__(self) -> str:
        """Get the hexadecimal representation of the script.

        Returns:
            The script data as a hex string.
        """
        return bytes(self).hex()

    def verify(
        self,
        amount: int,
        tx_to: "Transaction",
        precomputed_txdata: PrecomputedTransactionData | None,
        input_index: int,
        flags: ScriptVerificationFlags,
    ) -> bool:
        """Verify that a transaction input correctly spends this script pubkey.

        This function validates whether the input at the specified index in the
        spending transaction satisfies the conditions defined by the script pubkey.
        The verification process depends on the flags provided, which control which
        consensus rules are enforced.

        Args:
            amount: The value of the output being spent, in satoshis. Required
                when VERIFY_WITNESS flag is set.
            tx_to: The transaction that is attempting to spend the output.
            precomputed_txdata: Precomputed data for tx_to with the spent outputs. Required
                when VERIFY_TAPROOT flag is set, otherwise can be None.
            input_index: The zero-based index of the input in `tx_to` that is
                spending the script pubkey.
            flags: Bitfield of ScriptFlags controlling which validation rules to
                enforce. Use ScriptFlags values combined with bitwise OR.

        Returns:
            True if the input spends the script pubkey validly, False otherwise.

        Raises:
            ScriptVerifyException: If the verification could not run, e.g.
                because the flags were combined in an invalid way. The
                exception contains the status code.
        """
        k_status = k.btck_ScriptVerifyStatus(ScriptVerifyStatus.OK)
        success = k.btck_script_pubkey_verify(
            self,
            amount,
            tx_to,
            precomputed_txdata,
            ctypes.c_uint32(input_index),
            flags,
            k_status,
        )

        status = ScriptVerifyStatus(k_status.value)
        if not success and status != ScriptVerifyStatus.OK:
            raise ScriptVerifyException(status)

        return success

__bytes__

__bytes__() -> bytes

Serialize the script pubkey to bytes.

RETURNS DESCRIPTION
bytes

The raw script data.

Source code in pbk/script.py
def __bytes__(self) -> bytes:
    """Serialize the script pubkey to bytes.

    Returns:
        The raw script data.
    """
    writer = ByteWriter()
    return writer.write(k.btck_script_pubkey_to_bytes, self)

__init__

__init__(data: bytes)

Create a script pubkey from raw script data.

PARAMETER DESCRIPTION
data

The script pubkey data containing opcodes and operands.

TYPE: bytes

RAISES DESCRIPTION
RuntimeError

If the C constructor fails (propagated from base class).

Source code in pbk/script.py
def __init__(self, data: bytes):
    """Create a script pubkey from raw script data.

    Args:
        data: The script pubkey data containing opcodes and operands.

    Raises:
        RuntimeError: If the C constructor fails (propagated from base class).
    """
    super().__init__((ctypes.c_ubyte * len(data))(*data), len(data))

__repr__

__repr__() -> str

Return a string representation of the script pubkey.

Source code in pbk/script.py
def __repr__(self) -> str:
    """Return a string representation of the script pubkey."""
    hex_str = str(self)
    preview = hex_str[:32] + "..." if len(hex_str) > 32 else hex_str
    return f"<ScriptPubkey len={len(bytes(self))} hex={preview}>"

__str__

__str__() -> str

Get the hexadecimal representation of the script.

RETURNS DESCRIPTION
str

The script data as a hex string.

Source code in pbk/script.py
def __str__(self) -> str:
    """Get the hexadecimal representation of the script.

    Returns:
        The script data as a hex string.
    """
    return bytes(self).hex()

verify

verify(amount: int, tx_to: Transaction, precomputed_txdata: PrecomputedTransactionData | None, input_index: int, flags: ScriptVerificationFlags) -> bool

Verify that a transaction input correctly spends this script pubkey.

This function validates whether the input at the specified index in the spending transaction satisfies the conditions defined by the script pubkey. The verification process depends on the flags provided, which control which consensus rules are enforced.

PARAMETER DESCRIPTION
amount

The value of the output being spent, in satoshis. Required when VERIFY_WITNESS flag is set.

TYPE: int

tx_to

The transaction that is attempting to spend the output.

TYPE: Transaction

precomputed_txdata

Precomputed data for tx_to with the spent outputs. Required when VERIFY_TAPROOT flag is set, otherwise can be None.

TYPE: PrecomputedTransactionData | None

input_index

The zero-based index of the input in tx_to that is spending the script pubkey.

TYPE: int

flags

Bitfield of ScriptFlags controlling which validation rules to enforce. Use ScriptFlags values combined with bitwise OR.

TYPE: ScriptVerificationFlags

RETURNS DESCRIPTION
bool

True if the input spends the script pubkey validly, False otherwise.

RAISES DESCRIPTION
ScriptVerifyException

If the verification could not run, e.g. because the flags were combined in an invalid way. The exception contains the status code.

Source code in pbk/script.py
def verify(
    self,
    amount: int,
    tx_to: "Transaction",
    precomputed_txdata: PrecomputedTransactionData | None,
    input_index: int,
    flags: ScriptVerificationFlags,
) -> bool:
    """Verify that a transaction input correctly spends this script pubkey.

    This function validates whether the input at the specified index in the
    spending transaction satisfies the conditions defined by the script pubkey.
    The verification process depends on the flags provided, which control which
    consensus rules are enforced.

    Args:
        amount: The value of the output being spent, in satoshis. Required
            when VERIFY_WITNESS flag is set.
        tx_to: The transaction that is attempting to spend the output.
        precomputed_txdata: Precomputed data for tx_to with the spent outputs. Required
            when VERIFY_TAPROOT flag is set, otherwise can be None.
        input_index: The zero-based index of the input in `tx_to` that is
            spending the script pubkey.
        flags: Bitfield of ScriptFlags controlling which validation rules to
            enforce. Use ScriptFlags values combined with bitwise OR.

    Returns:
        True if the input spends the script pubkey validly, False otherwise.

    Raises:
        ScriptVerifyException: If the verification could not run, e.g.
            because the flags were combined in an invalid way. The
            exception contains the status code.
    """
    k_status = k.btck_ScriptVerifyStatus(ScriptVerifyStatus.OK)
    success = k.btck_script_pubkey_verify(
        self,
        amount,
        tx_to,
        precomputed_txdata,
        ctypes.c_uint32(input_index),
        flags,
        k_status,
    )

    status = ScriptVerifyStatus(k_status.value)
    if not success and status != ScriptVerifyStatus.OK:
        raise ScriptVerifyException(status)

    return success