Skip to content

Block

Block

Bases: KernelOpaquePtr

A deserialized Bitcoin block.

Source code in pbk/block.py
class Block(KernelOpaquePtr):
    """A deserialized Bitcoin block."""

    _create_fn = k.btck_block_create
    _destroy_fn = k.btck_block_destroy
    _copy_fn = k.btck_block_copy

    def __init__(self, raw_block: bytes):
        """Create a block from serialized data.

        Args:
            raw_block: The serialized block data in consensus format.

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

    @property
    def block_hash(self) -> BlockHash:
        """The hash of this block.

        Computes the double-SHA256 hash of the block header.

        Returns:
            The block hash. Owned handle.
        """
        return BlockHash._from_handle(k.btck_block_get_hash(self))

    @property
    def block_header(self) -> BlockHeader:
        """The header of this block.

        Returns:
            The block header. Owned handle.
        """
        return BlockHeader._from_handle(k.btck_block_get_header(self))

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

        Returns:
            The serialized block data in consensus format, suitable for
            P2P network transmission.
        """
        writer = ByteWriter()
        return writer.write(k.btck_block_to_bytes, self)

    def _get_transaction_at(self, transaction_index: int) -> Transaction:
        """Get the transaction at the given index."""
        return Transaction._from_view(
            k.btck_block_get_transaction_at(self, transaction_index), self
        )

    @property
    def transactions(self) -> TransactionSequence:
        """All transactions in this block.

        Returns:
            A lazy sequence of transactions, including the coinbase.
        """
        return TransactionSequence(self)

    def check(
        self,
        consensus_params: "ConsensusParams",
        flags: BlockCheckFlags = BlockCheckFlags.ALL,
    ) -> BlockValidationState:
        """Perform context-free validation checks on this block.

        Checks size limits, coinbase structure, per-transaction validity and
        sigop limits using the supplied consensus params. Proof-of-work and
        merkle-root checks are optional and toggled via `flags`. Does not
        include script, timestamp, ordering or other context-dependent checks.

        Args:
            consensus_params: The consensus parameters to validate against.
            flags: Bitmask controlling the optional POW and merkle-root checks.
                Defaults to `BlockCheckFlags.ALL`.

        Returns:
            The resulting validation state. Inspect `validation_mode` to
            determine whether the block passed. Owned handle.
        """
        state = BlockValidationState()
        ret = k.btck_block_check(self, consensus_params, flags, state)
        assert (ret == 1) == (state.validation_mode == ValidationMode.VALID)
        return state

    def __repr__(self) -> str:
        """Return a string representation of the block."""
        return f"<Block hash={str(self.block_hash)} txs={len(self.transactions)}>"

block_hash property

block_hash: BlockHash

The hash of this block.

Computes the double-SHA256 hash of the block header.

RETURNS DESCRIPTION
BlockHash

The block hash. Owned handle.

block_header property

block_header: BlockHeader

The header of this block.

RETURNS DESCRIPTION
BlockHeader

The block header. Owned handle.

transactions property

transactions: TransactionSequence

All transactions in this block.

RETURNS DESCRIPTION
TransactionSequence

A lazy sequence of transactions, including the coinbase.

__bytes__

__bytes__() -> bytes

Serialize the block to bytes.

RETURNS DESCRIPTION
bytes

The serialized block data in consensus format, suitable for

bytes

P2P network transmission.

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

    Returns:
        The serialized block data in consensus format, suitable for
        P2P network transmission.
    """
    writer = ByteWriter()
    return writer.write(k.btck_block_to_bytes, self)

__init__

__init__(raw_block: bytes)

Create a block from serialized data.

PARAMETER DESCRIPTION
raw_block

The serialized block data in consensus format.

TYPE: bytes

RAISES DESCRIPTION
RuntimeError

If parsing the block data fails (propagated from base class).

Source code in pbk/block.py
def __init__(self, raw_block: bytes):
    """Create a block from serialized data.

    Args:
        raw_block: The serialized block data in consensus format.

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

__repr__

__repr__() -> str

Return a string representation of the block.

Source code in pbk/block.py
def __repr__(self) -> str:
    """Return a string representation of the block."""
    return f"<Block hash={str(self.block_hash)} txs={len(self.transactions)}>"

check

check(consensus_params: ConsensusParams, flags: BlockCheckFlags = BlockCheckFlags.ALL) -> BlockValidationState

Perform context-free validation checks on this block.

Checks size limits, coinbase structure, per-transaction validity and sigop limits using the supplied consensus params. Proof-of-work and merkle-root checks are optional and toggled via flags. Does not include script, timestamp, ordering or other context-dependent checks.

PARAMETER DESCRIPTION
consensus_params

The consensus parameters to validate against.

TYPE: ConsensusParams

flags

Bitmask controlling the optional POW and merkle-root checks. Defaults to BlockCheckFlags.ALL.

TYPE: BlockCheckFlags DEFAULT: ALL

RETURNS DESCRIPTION
BlockValidationState

The resulting validation state. Inspect validation_mode to

BlockValidationState

determine whether the block passed. Owned handle.

Source code in pbk/block.py
def check(
    self,
    consensus_params: "ConsensusParams",
    flags: BlockCheckFlags = BlockCheckFlags.ALL,
) -> BlockValidationState:
    """Perform context-free validation checks on this block.

    Checks size limits, coinbase structure, per-transaction validity and
    sigop limits using the supplied consensus params. Proof-of-work and
    merkle-root checks are optional and toggled via `flags`. Does not
    include script, timestamp, ordering or other context-dependent checks.

    Args:
        consensus_params: The consensus parameters to validate against.
        flags: Bitmask controlling the optional POW and merkle-root checks.
            Defaults to `BlockCheckFlags.ALL`.

    Returns:
        The resulting validation state. Inspect `validation_mode` to
        determine whether the block passed. Owned handle.
    """
    state = BlockValidationState()
    ret = k.btck_block_check(self, consensus_params, flags, state)
    assert (ret == 1) == (state.validation_mode == ValidationMode.VALID)
    return state

BlockCheckFlags

Bases: IntFlag

Bitflags controlling optional context-free block checks.

These flags toggle the optional checks performed by Block.check. Multiple flags can be combined using bitwise OR operations.

Source code in pbk/block.py
class BlockCheckFlags(IntFlag):
    """Bitflags controlling optional context-free block checks.

    These flags toggle the optional checks performed by [Block.check][pbk.Block.check].
    Multiple flags can be combined using bitwise OR operations.
    """

    BASE = 0  #: Run only the base context-free block checks
    POW = 1 << 0  #: Run CheckProofOfWork via CheckBlockHeader
    MERKLE = 1 << 1  #: Verify the merkle root and detect mutation
    ALL = POW | MERKLE  #: Enable all optional context-free block checks

ALL class-attribute instance-attribute

ALL = POW | MERKLE

BASE class-attribute instance-attribute

BASE = 0

MERKLE class-attribute instance-attribute

MERKLE = 1 << 1

POW class-attribute instance-attribute

POW = 1 << 0

BlockHash

Bases: KernelOpaquePtr

Identifier for a block.

Source code in pbk/block.py
class BlockHash(KernelOpaquePtr):
    """Identifier for a block."""

    _create_fn = k.btck_block_hash_create
    _destroy_fn = k.btck_block_hash_destroy
    _copy_fn = k.btck_block_hash_copy

    def __init__(self, block_hash: bytes):
        """Create a block hash from raw bytes.

        Args:
            block_hash: The 32-byte block hash in little-endian byte order.

        Raises:
            ValueError: If the block hash is not exactly 32 bytes.
            RuntimeError: If the C constructor fails (propagated from base class).
        """
        if len(block_hash) != 32:
            raise ValueError(
                f"block_hash argument must be bytes of length 32, got {len(block_hash)}"
            )
        hash_array = (ctypes.c_ubyte * 32).from_buffer_copy(block_hash)
        super().__init__(hash_array)

    def __bytes__(self) -> bytes:
        """Serialize the block hash to bytes.

        Returns:
            The 32-byte block hash in little-endian byte order.
        """
        hash_array = (ctypes.c_ubyte * 32)()
        k.btck_block_hash_to_bytes(self, hash_array)
        return bytes(hash_array)

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

        Returns:
            The block hash as a 64-character hex string in big-endian
            byte order (standard Bitcoin display format).
        """
        # bytes are serialized in little-endian byte order, typically displayed in big-endian byte order
        return bytes(self)[::-1].hex()

    def __eq__(self, other: object) -> bool:
        """Check equality with another block hash.

        Args:
            other: Object to compare with.

        Returns:
            True if both are BlockHash instances with equal values.
        """
        if isinstance(other, BlockHash):
            return bool(k.btck_block_hash_equals(self, other))
        return False

    def __hash__(self) -> int:
        """Get hash value for use in sets and dictionaries.

        Returns:
            Hash of the block hash bytes.
        """
        return hash(bytes(self))

    def __repr__(self) -> str:
        """Return a string representation of the block hash."""
        return f"BlockHash({bytes(self)!r})"

__bytes__

__bytes__() -> bytes

Serialize the block hash to bytes.

RETURNS DESCRIPTION
bytes

The 32-byte block hash in little-endian byte order.

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

    Returns:
        The 32-byte block hash in little-endian byte order.
    """
    hash_array = (ctypes.c_ubyte * 32)()
    k.btck_block_hash_to_bytes(self, hash_array)
    return bytes(hash_array)

__eq__

__eq__(other: object) -> bool

Check equality with another block hash.

PARAMETER DESCRIPTION
other

Object to compare with.

TYPE: object

RETURNS DESCRIPTION
bool

True if both are BlockHash instances with equal values.

Source code in pbk/block.py
def __eq__(self, other: object) -> bool:
    """Check equality with another block hash.

    Args:
        other: Object to compare with.

    Returns:
        True if both are BlockHash instances with equal values.
    """
    if isinstance(other, BlockHash):
        return bool(k.btck_block_hash_equals(self, other))
    return False

__hash__

__hash__() -> int

Get hash value for use in sets and dictionaries.

RETURNS DESCRIPTION
int

Hash of the block hash bytes.

Source code in pbk/block.py
def __hash__(self) -> int:
    """Get hash value for use in sets and dictionaries.

    Returns:
        Hash of the block hash bytes.
    """
    return hash(bytes(self))

__init__

__init__(block_hash: bytes)

Create a block hash from raw bytes.

PARAMETER DESCRIPTION
block_hash

The 32-byte block hash in little-endian byte order.

TYPE: bytes

RAISES DESCRIPTION
ValueError

If the block hash is not exactly 32 bytes.

RuntimeError

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

Source code in pbk/block.py
def __init__(self, block_hash: bytes):
    """Create a block hash from raw bytes.

    Args:
        block_hash: The 32-byte block hash in little-endian byte order.

    Raises:
        ValueError: If the block hash is not exactly 32 bytes.
        RuntimeError: If the C constructor fails (propagated from base class).
    """
    if len(block_hash) != 32:
        raise ValueError(
            f"block_hash argument must be bytes of length 32, got {len(block_hash)}"
        )
    hash_array = (ctypes.c_ubyte * 32).from_buffer_copy(block_hash)
    super().__init__(hash_array)

__repr__

__repr__() -> str

Return a string representation of the block hash.

Source code in pbk/block.py
def __repr__(self) -> str:
    """Return a string representation of the block hash."""
    return f"BlockHash({bytes(self)!r})"

__str__

__str__() -> str

Get the hexadecimal representation of the block hash.

RETURNS DESCRIPTION
str

The block hash as a 64-character hex string in big-endian

str

byte order (standard Bitcoin display format).

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

    Returns:
        The block hash as a 64-character hex string in big-endian
        byte order (standard Bitcoin display format).
    """
    # bytes are serialized in little-endian byte order, typically displayed in big-endian byte order
    return bytes(self)[::-1].hex()

BlockHeader

Bases: KernelOpaquePtr

A deserialized Bitcoin block header.

Source code in pbk/block.py
class BlockHeader(KernelOpaquePtr):
    """A deserialized Bitcoin block header."""

    _create_fn = k.btck_block_header_create
    _destroy_fn = k.btck_block_header_destroy
    _copy_fn = k.btck_block_header_copy

    def __init__(self, raw_header: bytes):
        """Create a block header from serialized data.

        Args:
            raw_header: The serialized block header data in consensus format. Must be 80 bytes.

        Raises:
            RuntimeError: If parsing the block header data fails (propagated from base class)
        """
        if len(raw_header) != 80:
            raise ValueError(
                f"raw_header argument must be bytes of length 80, got {len(raw_header)}"
            )
        super().__init__((ctypes.c_ubyte * 80).from_buffer_copy(raw_header), 80)

    @property
    def block_hash(self) -> BlockHash:
        """The block hash.

        Returns:
            The block hash. Owned handle.
        """
        return BlockHash._from_handle(k.btck_block_header_get_hash(self))

    @property
    def prev_hash(self) -> BlockHash:
        """The previous block hash.

        Returns:
            The previous block hash. View into this header.
        """
        return BlockHash._from_view(k.btck_block_header_get_prev_hash(self), self)

    @property
    def timestamp(self) -> datetime.datetime:
        """The timestamp."""
        epoch = k.btck_block_header_get_timestamp(self)
        return datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)

    @property
    def bits(self) -> int:
        """The nBits difficulty target."""
        return k.btck_block_header_get_bits(self)

    @property
    def version(self) -> int:
        """The version."""
        return k.btck_block_header_get_version(self)

    @property
    def nonce(self) -> int:
        """The nonce."""
        return k.btck_block_header_get_nonce(self)

    def __bytes__(self) -> bytes:
        """Serialize the block header to bytes.

        Returns:
            The 80-byte serialized block header in consensus format.

        Raises:
            RuntimeError: If serialization fails.
        """
        output = (ctypes.c_ubyte * 80)()
        ret = k.btck_block_header_to_bytes(self, output)
        if ret != 0:
            raise RuntimeError(
                f"Block header serialization failed with return code {ret}"
            )
        return bytes(output)

    def __repr__(self) -> str:
        """Return a string representation of the block header."""
        return f"<Block header hash={str(self.block_hash)}>"

bits property

bits: int

The nBits difficulty target.

block_hash property

block_hash: BlockHash

The block hash.

RETURNS DESCRIPTION
BlockHash

The block hash. Owned handle.

nonce property

nonce: int

The nonce.

prev_hash property

prev_hash: BlockHash

The previous block hash.

RETURNS DESCRIPTION
BlockHash

The previous block hash. View into this header.

timestamp property

timestamp: datetime

The timestamp.

version property

version: int

The version.

__bytes__

__bytes__() -> bytes

Serialize the block header to bytes.

RETURNS DESCRIPTION
bytes

The 80-byte serialized block header in consensus format.

RAISES DESCRIPTION
RuntimeError

If serialization fails.

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

    Returns:
        The 80-byte serialized block header in consensus format.

    Raises:
        RuntimeError: If serialization fails.
    """
    output = (ctypes.c_ubyte * 80)()
    ret = k.btck_block_header_to_bytes(self, output)
    if ret != 0:
        raise RuntimeError(
            f"Block header serialization failed with return code {ret}"
        )
    return bytes(output)

__init__

__init__(raw_header: bytes)

Create a block header from serialized data.

PARAMETER DESCRIPTION
raw_header

The serialized block header data in consensus format. Must be 80 bytes.

TYPE: bytes

RAISES DESCRIPTION
RuntimeError

If parsing the block header data fails (propagated from base class)

Source code in pbk/block.py
def __init__(self, raw_header: bytes):
    """Create a block header from serialized data.

    Args:
        raw_header: The serialized block header data in consensus format. Must be 80 bytes.

    Raises:
        RuntimeError: If parsing the block header data fails (propagated from base class)
    """
    if len(raw_header) != 80:
        raise ValueError(
            f"raw_header argument must be bytes of length 80, got {len(raw_header)}"
        )
    super().__init__((ctypes.c_ubyte * 80).from_buffer_copy(raw_header), 80)

__repr__

__repr__() -> str

Return a string representation of the block header.

Source code in pbk/block.py
def __repr__(self) -> str:
    """Return a string representation of the block header."""
    return f"<Block header hash={str(self.block_hash)}>"

BlockTreeEntry

Bases: KernelOpaquePtr

Entry in the block tree.

A block tree entry represents a single block in the block tree maintained by the chainstate manager. Each entry (except genesis) points to a single parent, and multiple entries may share a parent, forming a tree structure. Each entry corresponds to a single block and may be used to retrieve its data and validation status.

Source code in pbk/block.py
class BlockTreeEntry(KernelOpaquePtr):
    """Entry in the block tree.

    A block tree entry represents a single block in the block tree
    maintained by the chainstate manager. Each entry (except genesis)
    points to a single parent, and multiple entries may share a parent,
    forming a tree structure. Each entry corresponds to a single block
    and may be used to retrieve its data and validation status.
    """

    @property
    def block_hash(self) -> BlockHash:
        """The hash of the block this entry represents.

        Returns:
            The block hash associated with this entry. View into this
            entry.
        """
        return BlockHash._from_view(k.btck_block_tree_entry_get_block_hash(self), self)

    @property
    def height(self) -> int:
        """The height of this block in the chain.

        Returns:
            The block height. Genesis block is at height 0.
        """
        return k.btck_block_tree_entry_get_height(self)

    @property
    def previous(self) -> "BlockTreeEntry":
        """The parent block tree entry.

        Returns:
            The previous block tree entry in the tree. View into the
            chainstate manager (transitively, via this entry's parent).

        Raises:
            RuntimeError: If the C constructor fails (propagated from base class).
        """
        return BlockTreeEntry._from_view(
            k.btck_block_tree_entry_get_previous(self), self._parent
        )

    @property
    def block_header(self) -> "BlockHeader":
        """The header of the block this entry represents.

        Returns:
            The block header. Owned handle.
        """
        return BlockHeader._from_handle(k.btck_block_tree_entry_get_block_header(self))

    def get_ancestor(self, height: int) -> "BlockTreeEntry":
        """Get the ancestor of this block tree entry at the given height.

        Args:
            height: The height of the requested ancestor. Must be between
                0 and this entry's height (inclusive).

        Returns:
            The block tree entry at the given height on the chain leading
            to this entry. View into the chainstate manager (transitively,
            via this entry's parent).

        Raises:
            ValueError: If `height` is negative or greater than this
                entry's height.
        """
        if height < 0 or height > self.height:
            raise ValueError(
                f"height {height} out of range for entry at height {self.height}"
            )
        return BlockTreeEntry._from_view(
            k.btck_block_tree_entry_get_ancestor(self, height), self._parent
        )

    def __eq__(self, other: object) -> bool:
        """Check equality with another block tree entry.

        Args:
            other: Object to compare with.

        Returns:
            True if both are BlockTreeEntry instances with equal height and hash.
        """
        if isinstance(other, BlockTreeEntry):
            return bool(k.btck_block_tree_entry_equals(self, other))
        return False

    def __hash__(self) -> int:
        """Get hash value for use in sets and dictionaries.

        Returns:
            Hash combining height and block hash.
        """
        return hash((self.height, bytes(self.block_hash)))

    def __repr__(self) -> str:
        """Return a string representation of the block tree entry."""
        return f"<BlockTreeEntry height={self.height} hash={str(self.block_hash)}>"

block_hash property

block_hash: BlockHash

The hash of the block this entry represents.

RETURNS DESCRIPTION
BlockHash

The block hash associated with this entry. View into this

BlockHash

entry.

block_header property

block_header: BlockHeader

The header of the block this entry represents.

RETURNS DESCRIPTION
BlockHeader

The block header. Owned handle.

height property

height: int

The height of this block in the chain.

RETURNS DESCRIPTION
int

The block height. Genesis block is at height 0.

previous property

previous: BlockTreeEntry

The parent block tree entry.

RETURNS DESCRIPTION
BlockTreeEntry

The previous block tree entry in the tree. View into the

BlockTreeEntry

chainstate manager (transitively, via this entry's parent).

RAISES DESCRIPTION
RuntimeError

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

__eq__

__eq__(other: object) -> bool

Check equality with another block tree entry.

PARAMETER DESCRIPTION
other

Object to compare with.

TYPE: object

RETURNS DESCRIPTION
bool

True if both are BlockTreeEntry instances with equal height and hash.

Source code in pbk/block.py
def __eq__(self, other: object) -> bool:
    """Check equality with another block tree entry.

    Args:
        other: Object to compare with.

    Returns:
        True if both are BlockTreeEntry instances with equal height and hash.
    """
    if isinstance(other, BlockTreeEntry):
        return bool(k.btck_block_tree_entry_equals(self, other))
    return False

__hash__

__hash__() -> int

Get hash value for use in sets and dictionaries.

RETURNS DESCRIPTION
int

Hash combining height and block hash.

Source code in pbk/block.py
def __hash__(self) -> int:
    """Get hash value for use in sets and dictionaries.

    Returns:
        Hash combining height and block hash.
    """
    return hash((self.height, bytes(self.block_hash)))

__repr__

__repr__() -> str

Return a string representation of the block tree entry.

Source code in pbk/block.py
def __repr__(self) -> str:
    """Return a string representation of the block tree entry."""
    return f"<BlockTreeEntry height={self.height} hash={str(self.block_hash)}>"

get_ancestor

get_ancestor(height: int) -> BlockTreeEntry

Get the ancestor of this block tree entry at the given height.

PARAMETER DESCRIPTION
height

The height of the requested ancestor. Must be between 0 and this entry's height (inclusive).

TYPE: int

RETURNS DESCRIPTION
BlockTreeEntry

The block tree entry at the given height on the chain leading

BlockTreeEntry

to this entry. View into the chainstate manager (transitively,

BlockTreeEntry

via this entry's parent).

RAISES DESCRIPTION
ValueError

If height is negative or greater than this entry's height.

Source code in pbk/block.py
def get_ancestor(self, height: int) -> "BlockTreeEntry":
    """Get the ancestor of this block tree entry at the given height.

    Args:
        height: The height of the requested ancestor. Must be between
            0 and this entry's height (inclusive).

    Returns:
        The block tree entry at the given height on the chain leading
        to this entry. View into the chainstate manager (transitively,
        via this entry's parent).

    Raises:
        ValueError: If `height` is negative or greater than this
            entry's height.
    """
    if height < 0 or height > self.height:
        raise ValueError(
            f"height {height} out of range for entry at height {self.height}"
        )
    return BlockTreeEntry._from_view(
        k.btck_block_tree_entry_get_ancestor(self, height), self._parent
    )

TransactionSequence

Bases: LazySequence[Transaction]

Lazily-evaluated sequence of transactions in a block.

This sequence provides indexed access to transactions within a block. The sequence is a view into the block and caches its length on first access.

Source code in pbk/block.py
class TransactionSequence(LazySequence[Transaction]):
    """Lazily-evaluated sequence of transactions in a block.

    This sequence provides indexed access to transactions within a block.
    The sequence is a view into the block and caches its length on first access.
    """

    def __init__(self, block: "Block"):
        """Create a sequence view of transactions.

        Args:
            block: The block to create a sequence view for.
        """
        self._block = block

    def __len__(self) -> int:
        """Number of transactions in the block.

        Returns:
            The transaction count (cached after first call).
        """
        if not hasattr(self, "_cached_len"):
            self._cached_len = k.btck_block_count_transactions(self._block)
        return self._cached_len

    def _get_item(self, index: int) -> Transaction:
        """Get the transaction at the given index."""
        return Transaction._from_view(
            k.btck_block_get_transaction_at(self._block, index), self._block
        )

__init__

__init__(block: Block)

Create a sequence view of transactions.

PARAMETER DESCRIPTION
block

The block to create a sequence view for.

TYPE: Block

Source code in pbk/block.py
def __init__(self, block: "Block"):
    """Create a sequence view of transactions.

    Args:
        block: The block to create a sequence view for.
    """
    self._block = block

__len__

__len__() -> int

Number of transactions in the block.

RETURNS DESCRIPTION
int

The transaction count (cached after first call).

Source code in pbk/block.py
def __len__(self) -> int:
    """Number of transactions in the block.

    Returns:
        The transaction count (cached after first call).
    """
    if not hasattr(self, "_cached_len"):
        self._cached_len = k.btck_block_count_transactions(self._block)
    return self._cached_len

TransactionSpentOutputsSequence

Bases: LazySequence[TransactionSpentOutputs]

Lazily-evaluated sequence of spent outputs for transactions in a block.

This sequence provides indexed access to the spent outputs (undo data) for each transaction in a block. The sequence excludes the coinbase transaction, which has no spent outputs.

Source code in pbk/block.py
class TransactionSpentOutputsSequence(LazySequence[TransactionSpentOutputs]):
    """Lazily-evaluated sequence of spent outputs for transactions in a block.

    This sequence provides indexed access to the spent outputs (undo data)
    for each transaction in a block. The sequence excludes the coinbase
    transaction, which has no spent outputs.
    """

    def __init__(self, block_spent_outputs: "BlockSpentOutputs"):
        """Create a sequence view of transaction spent outputs.

        Args:
            block_spent_outputs: The block spent outputs to create a sequence view for.
        """
        self._block_spent_outputs = block_spent_outputs

    def __len__(self) -> int:
        """Number of transaction spent outputs in the block. Equals the number of transactions in
        the block, minus 1 because the coinbase transaction is excluded as it has no spent outputs.

        Returns:
            The count of transaction spent outputs (cached after first call).
        """
        if not hasattr(self, "_cached_len"):
            self._cached_len = k.btck_block_spent_outputs_count(
                self._block_spent_outputs
            )
        return self._cached_len

    def _get_item(self, index: int) -> TransactionSpentOutputs:
        """Get the transaction spent outputs at the given index."""
        ptr = k.btck_block_spent_outputs_get_transaction_spent_outputs_at(
            self._block_spent_outputs, index
        )
        return TransactionSpentOutputs._from_view(ptr, self._block_spent_outputs)

__init__

__init__(block_spent_outputs: BlockSpentOutputs)

Create a sequence view of transaction spent outputs.

PARAMETER DESCRIPTION
block_spent_outputs

The block spent outputs to create a sequence view for.

TYPE: BlockSpentOutputs

Source code in pbk/block.py
def __init__(self, block_spent_outputs: "BlockSpentOutputs"):
    """Create a sequence view of transaction spent outputs.

    Args:
        block_spent_outputs: The block spent outputs to create a sequence view for.
    """
    self._block_spent_outputs = block_spent_outputs

__len__

__len__() -> int

Number of transaction spent outputs in the block. Equals the number of transactions in the block, minus 1 because the coinbase transaction is excluded as it has no spent outputs.

RETURNS DESCRIPTION
int

The count of transaction spent outputs (cached after first call).

Source code in pbk/block.py
def __len__(self) -> int:
    """Number of transaction spent outputs in the block. Equals the number of transactions in
    the block, minus 1 because the coinbase transaction is excluded as it has no spent outputs.

    Returns:
        The count of transaction spent outputs (cached after first call).
    """
    if not hasattr(self, "_cached_len"):
        self._cached_len = k.btck_block_spent_outputs_count(
            self._block_spent_outputs
        )
    return self._cached_len

BlockSpentOutputs

Bases: KernelOpaquePtr

Spent outputs (undo data) for all transactions in a block.

Block spent outputs contain all the previous outputs consumed by all transactions in a specific block. This data is also known as "undo data" because it's necessary for reverting blocks during chain reorganizations. The data is stored as a nested structure: a sequence of transaction spent outputs, each containing the coins consumed by that transaction's inputs.

Source code in pbk/block.py
class BlockSpentOutputs(KernelOpaquePtr):
    """Spent outputs (undo data) for all transactions in a block.

    Block spent outputs contain all the previous outputs consumed by all
    transactions in a specific block. This data is also known as "undo data"
    because it's necessary for reverting blocks during chain reorganizations.
    The data is stored as a nested structure: a sequence of transaction spent
    outputs, each containing the coins consumed by that transaction's inputs.
    """

    # Non-instantiable but can own pointers when read from disk
    _destroy_fn = k.btck_block_spent_outputs_destroy
    _copy_fn = k.btck_block_spent_outputs_copy

    def _get_transaction_spent_outputs_at(self, index: int) -> TransactionSpentOutputs:
        """Get the transaction spent outputs at the given index."""
        ptr = k.btck_block_spent_outputs_get_transaction_spent_outputs_at(self, index)
        return TransactionSpentOutputs._from_view(ptr, self)

    @property
    def transactions(self) -> TransactionSpentOutputsSequence:
        """Spent outputs for each transaction in the block.

        Returns:
            A sequence of transaction spent outputs, excluding the coinbase.
        """
        return TransactionSpentOutputsSequence(self)

    def __repr__(self) -> str:
        """Return a string representation of the block spent outputs."""
        return f"<BlockSpentOutputs txs={len(self.transactions)}>"

transactions property

transactions: TransactionSpentOutputsSequence

Spent outputs for each transaction in the block.

RETURNS DESCRIPTION
TransactionSpentOutputsSequence

A sequence of transaction spent outputs, excluding the coinbase.

__repr__

__repr__() -> str

Return a string representation of the block spent outputs.

Source code in pbk/block.py
def __repr__(self) -> str:
    """Return a string representation of the block spent outputs."""
    return f"<BlockSpentOutputs txs={len(self.transactions)}>"