Skip to content

Chain API

BlockMap

Bases: MapBase

Dictionary-like interface for reading blocks from disk.

This map reads blocks from disk using block tree entries as keys.

Source code in pbk/chain.py
class BlockMap(MapBase):
    """Dictionary-like interface for reading blocks from disk.

    This map reads blocks from disk using block tree entries as keys.
    """

    def __getitem__(self, key: BlockTreeEntry) -> Block:
        """Read a block from disk using its block tree entry.

        Args:
            key: The block tree entry identifying which block to read.

        Returns:
            The full block data read from disk.

        Raises:
            RuntimeError: If reading the block from disk fails.
        """
        entry = k.btck_block_read(self._chainman, key)
        if not entry:
            raise RuntimeError(f"Error reading Block for {key} from disk")
        return Block._from_handle(entry)

__getitem__

__getitem__(key: BlockTreeEntry) -> Block

Read a block from disk using its block tree entry.

PARAMETER DESCRIPTION
key

The block tree entry identifying which block to read.

TYPE: BlockTreeEntry

RETURNS DESCRIPTION
Block

The full block data read from disk.

RAISES DESCRIPTION
RuntimeError

If reading the block from disk fails.

Source code in pbk/chain.py
def __getitem__(self, key: BlockTreeEntry) -> Block:
    """Read a block from disk using its block tree entry.

    Args:
        key: The block tree entry identifying which block to read.

    Returns:
        The full block data read from disk.

    Raises:
        RuntimeError: If reading the block from disk fails.
    """
    entry = k.btck_block_read(self._chainman, key)
    if not entry:
        raise RuntimeError(f"Error reading Block for {key} from disk")
    return Block._from_handle(entry)

BlockSpentOutputsMap

Bases: MapBase

Dictionary-like interface for reading block spent outputs (undo data).

This map reads spent output data (also known as undo data) from disk.

Source code in pbk/chain.py
class BlockSpentOutputsMap(MapBase):
    """Dictionary-like interface for reading block spent outputs (undo data).

    This map reads spent output data (also known as undo data) from disk.
    """

    def __getitem__(self, key: BlockTreeEntry) -> BlockSpentOutputs:
        """Read block spent outputs from disk using a block tree entry.

        Args:
            key: The block tree entry identifying which block's spent outputs
                to read.

        Returns:
            The spent outputs data for the block.

        Raises:
            KeyError: If attempting to read spent outputs for the genesis block,
                which has no spent outputs.
            RuntimeError: If reading the spent outputs from disk fails.
        """
        if key.height == 0:
            raise KeyError("Genesis block does not have BlockSpentOutputs data")

        entry = k.btck_block_spent_outputs_read(self._chainman, key)
        if not entry:
            raise RuntimeError(f"Error reading BlockSpentOutputs for {key} from disk")
        return BlockSpentOutputs._from_handle(entry)

__getitem__

__getitem__(key: BlockTreeEntry) -> BlockSpentOutputs

Read block spent outputs from disk using a block tree entry.

PARAMETER DESCRIPTION
key

The block tree entry identifying which block's spent outputs to read.

TYPE: BlockTreeEntry

RETURNS DESCRIPTION
BlockSpentOutputs

The spent outputs data for the block.

RAISES DESCRIPTION
KeyError

If attempting to read spent outputs for the genesis block, which has no spent outputs.

RuntimeError

If reading the spent outputs from disk fails.

Source code in pbk/chain.py
def __getitem__(self, key: BlockTreeEntry) -> BlockSpentOutputs:
    """Read block spent outputs from disk using a block tree entry.

    Args:
        key: The block tree entry identifying which block's spent outputs
            to read.

    Returns:
        The spent outputs data for the block.

    Raises:
        KeyError: If attempting to read spent outputs for the genesis block,
            which has no spent outputs.
        RuntimeError: If reading the spent outputs from disk fails.
    """
    if key.height == 0:
        raise KeyError("Genesis block does not have BlockSpentOutputs data")

    entry = k.btck_block_spent_outputs_read(self._chainman, key)
    if not entry:
        raise RuntimeError(f"Error reading BlockSpentOutputs for {key} from disk")
    return BlockSpentOutputs._from_handle(entry)

BlockTreeEntryMap

Bases: MapBase

Dictionary-like interface for retrieving block tree entries by hash.

This map allows looking up block tree entries using their block hashes. It provides read-only dictionary access to the block index maintained by the chainstate manager.

Source code in pbk/chain.py
class BlockTreeEntryMap(MapBase):
    """Dictionary-like interface for retrieving block tree entries by hash.

    This map allows looking up block tree entries using their block hashes.
    It provides read-only dictionary access to the block index maintained
    by the chainstate manager.
    """

    def __getitem__(self, key: BlockHash) -> BlockTreeEntry:
        """Retrieve a block tree entry by its block hash.

        Args:
            key: The block hash to look up.

        Returns:
            The block tree entry corresponding to the hash.

        Raises:
            KeyError: If the block hash is not found in the block index.
        """
        entry = k.btck_chainstate_manager_get_block_tree_entry_by_hash(
            self._chainman, key
        )
        if not entry:
            raise KeyError(f"{key} not found")
        return BlockTreeEntry._from_view(entry)

__getitem__

__getitem__(key: BlockHash) -> BlockTreeEntry

Retrieve a block tree entry by its block hash.

PARAMETER DESCRIPTION
key

The block hash to look up.

TYPE: BlockHash

RETURNS DESCRIPTION
BlockTreeEntry

The block tree entry corresponding to the hash.

RAISES DESCRIPTION
KeyError

If the block hash is not found in the block index.

Source code in pbk/chain.py
def __getitem__(self, key: BlockHash) -> BlockTreeEntry:
    """Retrieve a block tree entry by its block hash.

    Args:
        key: The block hash to look up.

    Returns:
        The block tree entry corresponding to the hash.

    Raises:
        KeyError: If the block hash is not found in the block index.
    """
    entry = k.btck_chainstate_manager_get_block_tree_entry_by_hash(
        self._chainman, key
    )
    if not entry:
        raise KeyError(f"{key} not found")
    return BlockTreeEntry._from_view(entry)

BlockTreeEntrySequence

Bases: LazySequence[BlockTreeEntry]

Lazily-evaluated sequence of block tree entries in a chain.

This sequence provides access to the chain's block tree entries indexed by height. It supports iteration, length queries, and membership testing. The sequence is a view into the chain and reflects the current state. Its members and length may change during its lifetime, for example when blocks are added to the chain, or when a reorg happens.

Warning

The chain must not be mutated while iterating over this sequence. For example, if a reorg happens while iterating, there is no guarantee that the results belong to the same chain.

Source code in pbk/chain.py
class BlockTreeEntrySequence(LazySequence[BlockTreeEntry]):
    """Lazily-evaluated sequence of block tree entries in a chain.

    This sequence provides access to the chain's block tree entries indexed
    by height. It supports iteration, length queries, and membership testing.
    The sequence is a view into the chain and reflects the current state. Its
    members and length may change during its lifetime, for example when blocks
    are added to the chain, or when a reorg happens.

    !!! warning
        The chain must not be mutated while iterating over this sequence. For
        example, if a reorg happens while iterating, there is no guarantee that
        the results belong to the same chain.
    """

    def __init__(self, chain: "Chain"):
        """Create a sequence view of block tree entries.

        Args:
            chain: The chain object to create a sequence view for.
        """
        self._chain = chain

    def __len__(self) -> int:
        """The number of entries in the sequence."""
        return len(self._chain)

    def _get_item(self, index: int) -> BlockTreeEntry:
        """Get the block tree entry at the given height."""
        return BlockTreeEntry._from_view(k.btck_chain_get_by_height(self._chain, index))

    def __contains__(self, other: typing.Any):
        """Return True if `other` exists in the sequence."""
        if not isinstance(other, BlockTreeEntry):
            return False
        result = k.btck_chain_contains(self._chain, other)
        assert result in [0, 1]
        return bool(result)

__contains__

__contains__(other: Any)

Return True if other exists in the sequence.

Source code in pbk/chain.py
def __contains__(self, other: typing.Any):
    """Return True if `other` exists in the sequence."""
    if not isinstance(other, BlockTreeEntry):
        return False
    result = k.btck_chain_contains(self._chain, other)
    assert result in [0, 1]
    return bool(result)

__init__

__init__(chain: Chain)

Create a sequence view of block tree entries.

PARAMETER DESCRIPTION
chain

The chain object to create a sequence view for.

TYPE: Chain

Source code in pbk/chain.py
def __init__(self, chain: "Chain"):
    """Create a sequence view of block tree entries.

    Args:
        chain: The chain object to create a sequence view for.
    """
    self._chain = chain

__len__

__len__() -> int

The number of entries in the sequence.

Source code in pbk/chain.py
def __len__(self) -> int:
    """The number of entries in the sequence."""
    return len(self._chain)

ChainType

Bases: IntEnum

Enumeration of supported Bitcoin network types.

Source code in pbk/chain.py
class ChainType(IntEnum):
    """Enumeration of supported Bitcoin network types."""

    MAINNET = 0  #: Main Bitcoin network
    TESTNET = 1  #: Test Bitcoin network
    TESTNET_4 = 2  #: Testnet4 Bitcoin network
    SIGNET = 3  #: Signet Bitcoin network
    REGTEST = 4  #: Regression test network

MAINNET class-attribute instance-attribute

MAINNET = 0

REGTEST class-attribute instance-attribute

REGTEST = 4

SIGNET class-attribute instance-attribute

SIGNET = 3

TESTNET class-attribute instance-attribute

TESTNET = 1

TESTNET_4 class-attribute instance-attribute

TESTNET_4 = 2

ChainParameters

Bases: KernelOpaquePtr

Chain parameters describing properties of a Bitcoin network.

Chain parameters define network-specific constants and rules. These are typically passed to context options when creating a kernel context.

Source code in pbk/chain.py
class ChainParameters(KernelOpaquePtr):
    """Chain parameters describing properties of a Bitcoin network.

    Chain parameters define network-specific constants and rules. These
    are typically passed to [context options][pbk.ContextOptions] when
    creating a kernel context.
    """

    _create_fn = k.btck_chain_parameters_create
    _destroy_fn = k.btck_chain_parameters_destroy

    def __init__(self, chain_type: ChainType):
        """Create chain parameters for a specific network type.

        Args:
            chain_type: The Bitcoin network type to configure.

        Raises:
            RuntimeError: If the C constructor fails (propagated from base class).
        """
        super().__init__(chain_type)

__init__

__init__(chain_type: ChainType)

Create chain parameters for a specific network type.

PARAMETER DESCRIPTION
chain_type

The Bitcoin network type to configure.

TYPE: ChainType

RAISES DESCRIPTION
RuntimeError

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

Source code in pbk/chain.py
def __init__(self, chain_type: ChainType):
    """Create chain parameters for a specific network type.

    Args:
        chain_type: The Bitcoin network type to configure.

    Raises:
        RuntimeError: If the C constructor fails (propagated from base class).
    """
    super().__init__(chain_type)

ChainstateManagerOptions

Bases: KernelOpaquePtr

Configuration options for creating a chainstate manager.

These options specify how a chainstate manager should be initialized. Options need to be configured before passing it to a chainstate manager constructor.

Warning

Once a chainstate manager is initialized, changes to its options object are no longer reflected on the chainstate manager itself.

Source code in pbk/chain.py
class ChainstateManagerOptions(KernelOpaquePtr):
    """Configuration options for creating a [chainstate manager][pbk.ChainstateManager].

    These options specify how a chainstate manager should be initialized. Options need to be
    configured before passing it to a chainstate manager constructor.

    !!! warning
        Once a chainstate manager is initialized, changes to its options object are no longer
        reflected on the chainstate manager itself.
    """

    _create_fn = k.btck_chainstate_manager_options_create
    _destroy_fn = k.btck_chainstate_manager_options_destroy

    def __init__(self, context: "Context", datadir: str, blocks_dir: str):
        """Create chainstate manager options.

        Args:
            context: The kernel context to associate with.
            datadir: Non-empty path to the directory containing chainstate data. The
                directory will be created if it doesn't exist.
            blocks_dir: Non-empty path to the directory containing block data. The
                directory will be created if it doesn't exist.

        Raises:
            RuntimeError: If the C constructor fails due to invalid paths or
                other errors (propagated from base class).
        """
        datadir_bytes = datadir.encode("utf-8")
        blocksdir_bytes = blocks_dir.encode("utf-8")
        super().__init__(
            context,
            datadir_bytes,
            len(datadir_bytes),
            blocksdir_bytes,
            len(blocksdir_bytes),
        )

    def set_wipe_dbs(self, wipe_block_tree_db: bool, wipe_chainstate_db: bool) -> int:
        """Configure the wiping of the block tree database and the chainstate database.

        !!! warning
            If `wipe_block_tree_db==True`, [pbk.ChainstateManager.__init__][] and [pbk.ChainstateManager.import_blocks][]
            **must** be called for the wiping to take effect.


        Args:
            wipe_block_tree_db: Whether to wipe the block tree database.
                Should only be True if `wipe_chainstate_db` is also True.
            wipe_chainstate_db: Whether to wipe the chainstate database.

        Returns:
            0 if the configuration was successful, 1 otherwise.
        """
        return k.btck_chainstate_manager_options_set_wipe_dbs(
            self, wipe_block_tree_db, wipe_chainstate_db
        )

    def set_worker_threads_num(self, worker_threads: int):
        """Set the number of worker threads for parallel validation.

        Args:
            worker_threads: Number of worker threads for the validation thread
                pool. When set to 0, no parallel verification is performed.
                The value is internally clamped between 0 and 15.
        """
        k.btck_chainstate_manager_options_set_worker_threads_num(self, worker_threads)

    def update_block_tree_db_in_memory(self, block_tree_db_in_memory: bool):
        """Configure whether to use an in-memory block tree database.

        When enabled, the block tree database is stored in memory instead
        of on disk. Useful for testing or temporary validation tasks.

        Args:
            block_tree_db_in_memory: True to use in-memory storage,
                False to use disk storage.
        """
        k.btck_chainstate_manager_options_update_block_tree_db_in_memory(
            self, int(block_tree_db_in_memory)
        )

    def update_chainstate_db_in_memory(self, chainstate_db_in_memory: bool):
        """Configure whether to use an in-memory chainstate database.

        When enabled, the UTXO set and chainstate are stored in memory
        instead of on disk. Useful for testing or temporary validation tasks.

        Args:
            chainstate_db_in_memory: True to use in-memory storage,
                False to use disk storage.
        """
        k.btck_chainstate_manager_options_update_chainstate_db_in_memory(
            self, int(chainstate_db_in_memory)
        )

__init__

__init__(context: Context, datadir: str, blocks_dir: str)

Create chainstate manager options.

PARAMETER DESCRIPTION
context

The kernel context to associate with.

TYPE: Context

datadir

Non-empty path to the directory containing chainstate data. The directory will be created if it doesn't exist.

TYPE: str

blocks_dir

Non-empty path to the directory containing block data. The directory will be created if it doesn't exist.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the C constructor fails due to invalid paths or other errors (propagated from base class).

Source code in pbk/chain.py
def __init__(self, context: "Context", datadir: str, blocks_dir: str):
    """Create chainstate manager options.

    Args:
        context: The kernel context to associate with.
        datadir: Non-empty path to the directory containing chainstate data. The
            directory will be created if it doesn't exist.
        blocks_dir: Non-empty path to the directory containing block data. The
            directory will be created if it doesn't exist.

    Raises:
        RuntimeError: If the C constructor fails due to invalid paths or
            other errors (propagated from base class).
    """
    datadir_bytes = datadir.encode("utf-8")
    blocksdir_bytes = blocks_dir.encode("utf-8")
    super().__init__(
        context,
        datadir_bytes,
        len(datadir_bytes),
        blocksdir_bytes,
        len(blocksdir_bytes),
    )

set_wipe_dbs

set_wipe_dbs(wipe_block_tree_db: bool, wipe_chainstate_db: bool) -> int

Configure the wiping of the block tree database and the chainstate database.

Warning

If wipe_block_tree_db==True, pbk.ChainstateManager.init and pbk.ChainstateManager.import_blocks must be called for the wiping to take effect.

PARAMETER DESCRIPTION
wipe_block_tree_db

Whether to wipe the block tree database. Should only be True if wipe_chainstate_db is also True.

TYPE: bool

wipe_chainstate_db

Whether to wipe the chainstate database.

TYPE: bool

RETURNS DESCRIPTION
int

0 if the configuration was successful, 1 otherwise.

Source code in pbk/chain.py
def set_wipe_dbs(self, wipe_block_tree_db: bool, wipe_chainstate_db: bool) -> int:
    """Configure the wiping of the block tree database and the chainstate database.

    !!! warning
        If `wipe_block_tree_db==True`, [pbk.ChainstateManager.__init__][] and [pbk.ChainstateManager.import_blocks][]
        **must** be called for the wiping to take effect.


    Args:
        wipe_block_tree_db: Whether to wipe the block tree database.
            Should only be True if `wipe_chainstate_db` is also True.
        wipe_chainstate_db: Whether to wipe the chainstate database.

    Returns:
        0 if the configuration was successful, 1 otherwise.
    """
    return k.btck_chainstate_manager_options_set_wipe_dbs(
        self, wipe_block_tree_db, wipe_chainstate_db
    )

set_worker_threads_num

set_worker_threads_num(worker_threads: int)

Set the number of worker threads for parallel validation.

PARAMETER DESCRIPTION
worker_threads

Number of worker threads for the validation thread pool. When set to 0, no parallel verification is performed. The value is internally clamped between 0 and 15.

TYPE: int

Source code in pbk/chain.py
def set_worker_threads_num(self, worker_threads: int):
    """Set the number of worker threads for parallel validation.

    Args:
        worker_threads: Number of worker threads for the validation thread
            pool. When set to 0, no parallel verification is performed.
            The value is internally clamped between 0 and 15.
    """
    k.btck_chainstate_manager_options_set_worker_threads_num(self, worker_threads)

update_block_tree_db_in_memory

update_block_tree_db_in_memory(block_tree_db_in_memory: bool)

Configure whether to use an in-memory block tree database.

When enabled, the block tree database is stored in memory instead of on disk. Useful for testing or temporary validation tasks.

PARAMETER DESCRIPTION
block_tree_db_in_memory

True to use in-memory storage, False to use disk storage.

TYPE: bool

Source code in pbk/chain.py
def update_block_tree_db_in_memory(self, block_tree_db_in_memory: bool):
    """Configure whether to use an in-memory block tree database.

    When enabled, the block tree database is stored in memory instead
    of on disk. Useful for testing or temporary validation tasks.

    Args:
        block_tree_db_in_memory: True to use in-memory storage,
            False to use disk storage.
    """
    k.btck_chainstate_manager_options_update_block_tree_db_in_memory(
        self, int(block_tree_db_in_memory)
    )

update_chainstate_db_in_memory

update_chainstate_db_in_memory(chainstate_db_in_memory: bool)

Configure whether to use an in-memory chainstate database.

When enabled, the UTXO set and chainstate are stored in memory instead of on disk. Useful for testing or temporary validation tasks.

PARAMETER DESCRIPTION
chainstate_db_in_memory

True to use in-memory storage, False to use disk storage.

TYPE: bool

Source code in pbk/chain.py
def update_chainstate_db_in_memory(self, chainstate_db_in_memory: bool):
    """Configure whether to use an in-memory chainstate database.

    When enabled, the UTXO set and chainstate are stored in memory
    instead of on disk. Useful for testing or temporary validation tasks.

    Args:
        chainstate_db_in_memory: True to use in-memory storage,
            False to use disk storage.
    """
    k.btck_chainstate_manager_options_update_chainstate_db_in_memory(
        self, int(chainstate_db_in_memory)
    )

Chain

Bases: KernelOpaquePtr

View of the currently active blockchain.

This object represents the best-known chain and provides access to its block tree entries via height-based indexing. It is a dynamic view that always reflects the current active chain, but its contents may change when the chainstate manager processes new blocks or reorgs occur.

Note

The chain is a view with lifetime dependent on the chainstate manager it was retrieved from. Data retrieved from the chain is only consistent until new blocks are processed in the chainstate manager.

Source code in pbk/chain.py
class Chain(KernelOpaquePtr):
    """View of the currently active blockchain.

    This object represents the best-known chain and provides access to
    its block tree entries via height-based indexing. It is a dynamic view that always
    reflects the current active chain, but its contents may change when
    the chainstate manager processes new blocks or reorgs occur.

    Note:
        The chain is a view with lifetime dependent on the chainstate manager
        it was retrieved from. Data retrieved from the chain is only consistent
        until new blocks are processed in the chainstate manager.
    """

    @property
    def height(self) -> int:
        """Current height of the chain tip.

        Returns:
            Height of the chain tip. Genesis block is at height 0.
        """
        return k.btck_chain_get_height(self)

    def _get_by_height(self, height: int) -> BlockTreeEntry:
        """Get the block tree entry at the given height."""
        return BlockTreeEntry._from_view(k.btck_chain_get_by_height(self, height))

    @property
    def block_tree_entries(self) -> BlockTreeEntrySequence:
        """Sequence of all block tree entries in the chain.

        Returns:
            A lazy sequence supporting indexing and iteration over blocks
            in the chain by height.
        """
        return BlockTreeEntrySequence(self)

    def __len__(self) -> int:
        """Number of blocks in the chain."""
        return self.height + 1

    def __repr__(self) -> str:
        """Return a string representation of the chain."""
        return f"<Chain height={self.height}>"

block_tree_entries property

block_tree_entries: BlockTreeEntrySequence

Sequence of all block tree entries in the chain.

RETURNS DESCRIPTION
BlockTreeEntrySequence

A lazy sequence supporting indexing and iteration over blocks

BlockTreeEntrySequence

in the chain by height.

height property

height: int

Current height of the chain tip.

RETURNS DESCRIPTION
int

Height of the chain tip. Genesis block is at height 0.

__len__

__len__() -> int

Number of blocks in the chain.

Source code in pbk/chain.py
def __len__(self) -> int:
    """Number of blocks in the chain."""
    return self.height + 1

__repr__

__repr__() -> str

Return a string representation of the chain.

Source code in pbk/chain.py
def __repr__(self) -> str:
    """Return a string representation of the chain."""
    return f"<Chain height={self.height}>"

ChainstateManager

Bases: KernelOpaquePtr

Central manager for blockchain validation and data retrieval.

The chainstate manager is the primary interface for validation tasks and accessing blockchain data. It maintains the block index, UTXO set, and active chain. This is a complex internal data structure that will expose more functionality over time.

The chainstate manager can be safely used from multiple threads.

Source code in pbk/chain.py
class ChainstateManager(KernelOpaquePtr):
    """Central manager for blockchain validation and data retrieval.

    The chainstate manager is the primary interface for validation tasks
    and accessing blockchain data. It maintains the block index, UTXO set,
    and active chain. This is a complex internal data structure that will
    expose more functionality over time.

    The chainstate manager can be safely used from multiple threads.
    """

    _create_fn = k.btck_chainstate_manager_create
    _destroy_fn = k.btck_chainstate_manager_destroy

    def __init__(
        self,
        chain_man_opts: ChainstateManagerOptions,
    ):
        """Create a chainstate manager.

        !!! info
            If wiping options were [set][pbk.ChainstateManagerOptions.set_wipe_dbs] to
            `(wipe_block_tree_db==False, wipe_chainstate_db==True)`, the chainstate database will be
            rebuilt during initialization. This may take a long time.

        !!! info
            `bitcoinkernel` requires exclusive access to its data directories. The construction
            of a chainstate manager will fail if another process (e.g. Bitcoin Core) is currently
            using them.

        Args:
            chain_man_opts: Configuration options specifying data directories
                and other initialization parameters.

        Raises:
            TypeError: If instantiation is not supported (propagated from base class).
            RuntimeError: If creation fails due to invalid options, corrupted
                databases, or other errors (propagated from base class).
        """
        super().__init__(chain_man_opts)

    @property
    def block_tree_entries(self) -> BlockTreeEntryMap:
        """Dictionary-like interface for looking up block tree entries by hash.

        Returns:
            A map that retrieves block tree entries using block hashes as keys.
        """
        return BlockTreeEntryMap(self)

    def get_active_chain(self) -> Chain:
        """Get the currently active best-known blockchain.

        Returns a view of the active chain that always reflects the current
        best chain. Note that the chain's contents may change as new blocks
        are processed or as a reorg occurs.

        Returns:
            The active chain view.
        """
        return Chain._from_view(k.btck_chainstate_manager_get_active_chain(self))

    def import_blocks(self, paths: typing.List[Path]) -> bool:
        """Import blocks from block files.

        Args:
            paths: List of filesystem paths to block files to import.

        Returns:
            True if the import completed successfully, False otherwise.
        """
        encoded_paths = [str(path).encode("utf-8") for path in paths]

        block_file_paths = (ctypes.c_char_p * len(encoded_paths))()
        block_file_paths[:] = encoded_paths
        block_file_paths_lens = (ctypes.c_size_t * len(encoded_paths))()
        block_file_paths_lens[:] = [len(path) for path in encoded_paths]

        return k.btck_chainstate_manager_import_blocks(
            self,
            ctypes.cast(
                block_file_paths, ctypes.POINTER(ctypes.POINTER(ctypes.c_char))
            ),
            block_file_paths_lens,
            len(paths),
        )

    def process_block(self, block: Block) -> bool:
        """Process and validate the passed in block with the chainstate manager.

        Processing first does checks on the block, and if these passed, saves it to disk.
        It then validates the block against the utxo set. If it is valid, the chain is
        extended with it.

        Args:
            block: The block to process.

        Returns:
            True if the block was not processed and saved to disk before, False otherwise.

        Raises:
            ProcessBlockException: If processing the block failed. Duplicate blocks do not throw.
        """
        is_new_block = ctypes.c_int()
        result = k.btck_chainstate_manager_process_block(
            self, block, ctypes.pointer(is_new_block)
        )
        if result != 0:
            raise ProcessBlockException(result)
        assert is_new_block.value in [0, 1]
        return bool(is_new_block.value)

    @property
    def blocks(self) -> BlockMap:
        """Dictionary-like interface for reading blocks from disk.

        Returns:
            A map that reads full block data using block tree entries as keys.
        """
        return BlockMap(self)

    @property
    def block_spent_outputs(self) -> BlockSpentOutputsMap:
        """Dictionary-like interface for reading block spent outputs (undo data).

        Returns:
            A map that reads spent output data using block tree entries as keys.
        """
        return BlockSpentOutputsMap(self)

    def __repr__(self) -> str:
        """Return a string representation of the chainstate manager."""
        return f"<ChainstateManager at {hex(id(self))}>"

block_spent_outputs property

block_spent_outputs: BlockSpentOutputsMap

Dictionary-like interface for reading block spent outputs (undo data).

RETURNS DESCRIPTION
BlockSpentOutputsMap

A map that reads spent output data using block tree entries as keys.

block_tree_entries property

block_tree_entries: BlockTreeEntryMap

Dictionary-like interface for looking up block tree entries by hash.

RETURNS DESCRIPTION
BlockTreeEntryMap

A map that retrieves block tree entries using block hashes as keys.

blocks property

blocks: BlockMap

Dictionary-like interface for reading blocks from disk.

RETURNS DESCRIPTION
BlockMap

A map that reads full block data using block tree entries as keys.

__init__

__init__(chain_man_opts: ChainstateManagerOptions)

Create a chainstate manager.

Info

If wiping options were set to (wipe_block_tree_db==False, wipe_chainstate_db==True), the chainstate database will be rebuilt during initialization. This may take a long time.

Info

bitcoinkernel requires exclusive access to its data directories. The construction of a chainstate manager will fail if another process (e.g. Bitcoin Core) is currently using them.

PARAMETER DESCRIPTION
chain_man_opts

Configuration options specifying data directories and other initialization parameters.

TYPE: ChainstateManagerOptions

RAISES DESCRIPTION
TypeError

If instantiation is not supported (propagated from base class).

RuntimeError

If creation fails due to invalid options, corrupted databases, or other errors (propagated from base class).

Source code in pbk/chain.py
def __init__(
    self,
    chain_man_opts: ChainstateManagerOptions,
):
    """Create a chainstate manager.

    !!! info
        If wiping options were [set][pbk.ChainstateManagerOptions.set_wipe_dbs] to
        `(wipe_block_tree_db==False, wipe_chainstate_db==True)`, the chainstate database will be
        rebuilt during initialization. This may take a long time.

    !!! info
        `bitcoinkernel` requires exclusive access to its data directories. The construction
        of a chainstate manager will fail if another process (e.g. Bitcoin Core) is currently
        using them.

    Args:
        chain_man_opts: Configuration options specifying data directories
            and other initialization parameters.

    Raises:
        TypeError: If instantiation is not supported (propagated from base class).
        RuntimeError: If creation fails due to invalid options, corrupted
            databases, or other errors (propagated from base class).
    """
    super().__init__(chain_man_opts)

__repr__

__repr__() -> str

Return a string representation of the chainstate manager.

Source code in pbk/chain.py
def __repr__(self) -> str:
    """Return a string representation of the chainstate manager."""
    return f"<ChainstateManager at {hex(id(self))}>"

get_active_chain

get_active_chain() -> Chain

Get the currently active best-known blockchain.

Returns a view of the active chain that always reflects the current best chain. Note that the chain's contents may change as new blocks are processed or as a reorg occurs.

RETURNS DESCRIPTION
Chain

The active chain view.

Source code in pbk/chain.py
def get_active_chain(self) -> Chain:
    """Get the currently active best-known blockchain.

    Returns a view of the active chain that always reflects the current
    best chain. Note that the chain's contents may change as new blocks
    are processed or as a reorg occurs.

    Returns:
        The active chain view.
    """
    return Chain._from_view(k.btck_chainstate_manager_get_active_chain(self))

import_blocks

import_blocks(paths: List[Path]) -> bool

Import blocks from block files.

PARAMETER DESCRIPTION
paths

List of filesystem paths to block files to import.

TYPE: List[Path]

RETURNS DESCRIPTION
bool

True if the import completed successfully, False otherwise.

Source code in pbk/chain.py
def import_blocks(self, paths: typing.List[Path]) -> bool:
    """Import blocks from block files.

    Args:
        paths: List of filesystem paths to block files to import.

    Returns:
        True if the import completed successfully, False otherwise.
    """
    encoded_paths = [str(path).encode("utf-8") for path in paths]

    block_file_paths = (ctypes.c_char_p * len(encoded_paths))()
    block_file_paths[:] = encoded_paths
    block_file_paths_lens = (ctypes.c_size_t * len(encoded_paths))()
    block_file_paths_lens[:] = [len(path) for path in encoded_paths]

    return k.btck_chainstate_manager_import_blocks(
        self,
        ctypes.cast(
            block_file_paths, ctypes.POINTER(ctypes.POINTER(ctypes.c_char))
        ),
        block_file_paths_lens,
        len(paths),
    )

process_block

process_block(block: Block) -> bool

Process and validate the passed in block with the chainstate manager.

Processing first does checks on the block, and if these passed, saves it to disk. It then validates the block against the utxo set. If it is valid, the chain is extended with it.

PARAMETER DESCRIPTION
block

The block to process.

TYPE: Block

RETURNS DESCRIPTION
bool

True if the block was not processed and saved to disk before, False otherwise.

RAISES DESCRIPTION
ProcessBlockException

If processing the block failed. Duplicate blocks do not throw.

Source code in pbk/chain.py
def process_block(self, block: Block) -> bool:
    """Process and validate the passed in block with the chainstate manager.

    Processing first does checks on the block, and if these passed, saves it to disk.
    It then validates the block against the utxo set. If it is valid, the chain is
    extended with it.

    Args:
        block: The block to process.

    Returns:
        True if the block was not processed and saved to disk before, False otherwise.

    Raises:
        ProcessBlockException: If processing the block failed. Duplicate blocks do not throw.
    """
    is_new_block = ctypes.c_int()
    result = k.btck_chainstate_manager_process_block(
        self, block, ctypes.pointer(is_new_block)
    )
    if result != 0:
        raise ProcessBlockException(result)
    assert is_new_block.value in [0, 1]
    return bool(is_new_block.value)