ContextBuilder

Struct ContextBuilder 

Source
pub struct ContextBuilder { /* private fields */ }
Expand description

Builder for creating a Context with custom configuration.

The builder pattern allows flexible configuration of the Bitcoin Kernel context before creation. By default, the builder configures for mainnet with no callbacks registered.

§Configuration Options

  • Chain type: Set via chain_type
  • Notification callbacks: Set via with_*_notification methods or notifications
  • Validation callbacks: Set via with_*_validation methods or validation

§Examples

§Basic Configuration

use bitcoinkernel::{ContextBuilder, ChainType, KernelError};

let context = ContextBuilder::new()
    .chain_type(ChainType::Regtest)
    .build()?;

§With Individual Callbacks

use bitcoinkernel::{ContextBuilder, ChainType, KernelError};

let context = ContextBuilder::new()
    .chain_type(ChainType::Testnet)
    .with_progress_notification(|title, percent, _resume| {
        println!("Progress: {} - {}%", title, percent);
    })
    .with_block_tip_notification(|_state, hash, _progress| {
        println!("New tip: {}", hash);
    })
    .build()?;

§With Advanced Configuration

use bitcoinkernel::{Block, BlockValidationStateRef, ContextBuilder, ChainType, KernelError};

let context = ContextBuilder::new()
    .chain_type(ChainType::Regtest)
    .notifications(|registry| {
        registry.register_progress(|title, percent, _resume| {
            println!("{}: {}%", title, percent);
        });
        registry.register_warning_set(|warning, message| {
            eprintln!("Warning: {} - {}", warning, message);
        });
    })
    .validation(|registry| {
        registry.register_block_checked(|block: Block, _state: BlockValidationStateRef<'_>| {
            println!("Checked block: {}", block.hash());
        });
    })
    .build()?;

Implementations§

Source§

impl ContextBuilder

Source

pub fn new() -> ContextBuilder

Creates a new context builder with default settings.

The builder is initialized with mainnet configuration and no callbacks.

§Returns

A new ContextBuilder instance.

§Example
use bitcoinkernel::ContextBuilder;

let builder = ContextBuilder::new();
Source

pub fn build(self) -> Result<Context, KernelError>

Consumes the builder and creates a Context.

This finalizes the configuration and creates the actual context instance. All registered callbacks are set up during this process.

§Returns
§Example
use bitcoinkernel::{ContextBuilder, ChainType, KernelError};

let context = ContextBuilder::new()
    .chain_type(ChainType::Regtest)
    .build()?;
Source

pub fn chain_type(self, chain_type: ChainType) -> ContextBuilder

Sets the Bitcoin network chain type.

Configures the context to operate on the specified Bitcoin network.

§Arguments
  • chain_type - The ChainType to configure (mainnet, testnet, etc.)
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, ChainType, KernelError};

let context = ContextBuilder::new()
    .chain_type(ChainType::Regtest)
    .build()?;
Source

pub fn with_block_tip_notification<T>(self, handler: T) -> Self
where T: BlockTipCallback + 'static,

Registers a callback for block tip notifications.

The callback is invoked when the chain’s tip is updated to a new block. This happens during block validation and chain reorganizations.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • state - The SynchronizationState (initial download, etc.)
    • hash - The BlockHash of the new tip
    • progress - Verification progress as an f64 (0.0 to 1.0)
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_block_tip_notification(|_state, hash, progress| {
        println!("Chain tip updated to: {} ({})", hash, progress);
    })
    .build()?;
Source

pub fn with_progress_notification<T>(self, handler: T) -> Self
where T: ProgressCallback + 'static,

Registers a callback for progress notifications.

The callback is invoked to report on current block synchronization progress during operations such as initial block download or reindexing.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • title - Description of the current operation as a String
    • percent - Progress percentage as an i32 (0-100)
    • resume - Whether the operation can be resumed if interrupted (as a bool)
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_progress_notification(|title, percent, resume| {
        println!("{}: {}% (resumable: {})", title, percent, resume);
    })
    .build()?;
Source

pub fn with_header_tip_notification<T>(self, handler: T) -> Self
where T: HeaderTipCallback + 'static,

Registers a callback for header tip notifications.

The callback is invoked when a new best block header is added to the header chain. This typically occurs during the header synchronization phase, which happens before full block download.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • state - The SynchronizationState
    • height - The height of the new header tip as an i64
    • timestamp - The timestamp of the header as an i64
    • presync - Whether this is during pre-synchronization (as a bool)
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_header_tip_notification(|_state, height, timestamp, _presync| {
        println!("New header at height {}, time={}", height, timestamp);
    })
    .build()?;
Source

pub fn with_warning_set_notification<T>(self, handler: T) -> Self
where T: WarningSetCallback + 'static,

Registers a callback for warning set notifications.

The callback is invoked when a warning is issued by the kernel library during validation. This can include warnings about chain forks or other consensus-related issues.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • warning - A Warning identifier/category
    • message - A human-readable description as a String
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_warning_set_notification(|warning, message| {
        eprintln!("Kernel Warning [{}]: {}", warning, message);
    })
    .build()?;
Source

pub fn with_warning_unset_notification<T>(self, handler: T) -> Self
where T: WarningUnsetCallback + 'static,

Registers a callback for warning unset notifications.

The callback is invoked when a previous condition that led to the issuance of a warning is no longer present. This indicates that the warning condition has been resolved.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • warning - The Warning identifier/category that was cleared
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_warning_unset_notification(|warning| {
        println!("Warning [{}] has been cleared", warning);
    })
    .build()?;
Source

pub fn with_flush_error_notification<T>(self, handler: T) -> Self
where T: FlushErrorCallback + 'static,

Registers a callback for flush error notifications.

The callback is invoked when an error occurs while flushing data to disk.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • message - The error message as a String
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_flush_error_notification(|message| {
        eprintln!("Flush error: {}", message);
    })
    .build()?;
Source

pub fn with_fatal_error_notification<T>(self, handler: T) -> Self
where T: FatalErrorCallback + 'static,

Registers a callback for fatal error notifications.

The callback is invoked when an unrecoverable system error is encountered by the library. These are critical errors that typically require the application to shut down gracefully.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • message - A description of the fatal error as a String
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_fatal_error_notification(|message| {
        eprintln!("FATAL ERROR: {}", message);
        // Perform cleanup and shutdown
        std::process::exit(1);
    })
    .build()?;
Source

pub fn notifications<F>(self, configure: F) -> Self

Configures multiple notification callbacks at once.

This method provides access to the NotificationCallbackRegistry for advanced configuration of multiple callbacks.

§Type Parameters
  • F - A closure taking a mutable reference to the registry
§Arguments
  • configure - A closure that configures the notification registry
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .notifications(|registry| {
        registry.register_progress(|title, percent, _resume| {
            println!("{}: {}%", title, percent);
        });
        registry.register_block_tip(|_state, hash, _progress| {
            println!("Tip: {}", hash);
        });
        registry.register_warning_set(|_warning, msg| {
            eprintln!("Warning: {}", msg);
        });
    })
    .build()?;
Source

pub fn with_block_checked_validation<T>(self, handler: T) -> Self
where T: BlockCheckedCallback + 'static,

Registers a callback for block checked validation events.

The callback is invoked when a new block has been fully validated. The validation state contains the result of the validation, including whether the block is valid and any rejection reasons if invalid.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{
    prelude::*, Block, BlockValidationStateRef, ContextBuilder,
    KernelError, ValidationMode,
};

let context = ContextBuilder::new()
    .with_block_checked_validation(|block: Block, state: BlockValidationStateRef<'_>| {
        println!("Block validated: {}", block.hash());
        if state.mode() != ValidationMode::Valid {
            eprintln!("Validation failed with result: {:?}", state.result());
        }
    })
    .build()?;
Source

pub fn with_new_pow_valid_block_validation<T>(self, handler: T) -> Self
where T: NewPoWValidBlockCallback + 'static,

Registers a callback for new proof-of-work valid block events.

The callback is invoked when a new block extends the header chain and has a valid transaction and segwit merkle root.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{Block, BlockTreeEntry, ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_new_pow_valid_block_validation(|entry: BlockTreeEntry<'_>, block: Block| {
        println!("New PoW-valid block at height {}: {}",
                 entry.height(), block.hash());
    })
    .build()?;
Source

pub fn with_block_connected_validation<T>(self, handler: T) -> Self
where T: BlockConnectedCallback + 'static,

Registers a callback for block connected events.

The callback is invoked when a block is valid and has now been connected to the best chain. This happens after the block passes full validation and becomes part of the active chain.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • block - The Block that was connected
    • entry - The BlockTreeEntry representing the block’s position in the chain
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{Block, BlockTreeEntry, ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_block_connected_validation(|block: Block, entry: BlockTreeEntry<'_>| {
        println!("Block connected at height {}: {}",
                 entry.height(), block.hash());
    })
    .build()?;
Source

pub fn with_block_disconnected_validation<T>(self, handler: T) -> Self
where T: BlockDisconnectedCallback + 'static,

Registers a callback for block disconnected events.

The callback is invoked during a reorganization when a block has been removed from the best chain. This occurs when a competing chain with more cumulative work becomes the new active chain, requiring blocks from the old chain to be disconnected.

§Type Parameters
§Arguments
  • handler - The callback function or closure that receives:
    • block - The Block that was disconnected
    • entry - The BlockTreeEntry for the disconnected block
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{Block, BlockTreeEntry, ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .with_block_disconnected_validation(|block: Block, entry: BlockTreeEntry<'_>| {
        println!("Block disconnected from height {}: {} (reorg)",
                 entry.height(), block.hash());
    })
    .build()?;
Source

pub fn validation<F>(self, configure: F) -> Self

Configures multiple validation callbacks at once.

This method provides access to the ValidationCallbackRegistry for advanced configuration of multiple validation callbacks.

§Type Parameters
  • F - A closure taking a mutable reference to the registry
§Arguments
  • configure - A closure that configures the validation registry
§Returns

The builder instance for method chaining.

§Example
use bitcoinkernel::{Block, BlockTreeEntry, BlockValidationStateRef, ContextBuilder, KernelError};

let context = ContextBuilder::new()
    .validation(|registry| {
        registry.register_block_checked(|block: Block, _state: BlockValidationStateRef<'_>| {
            println!("Checked: {}", block.hash());
        });
        registry.register_block_connected(|_block, entry: BlockTreeEntry<'_>| {
            println!("Connected at height {}", entry.height());
        });
        registry.register_block_disconnected(|_block, entry: BlockTreeEntry<'_>| {
            println!("Disconnected from height {}", entry.height());
        });
    })
    .build()?;

Trait Implementations§

Source§

impl Default for ContextBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for ContextBuilder

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.