API Reference

class bdkpython.bdk.Address(address: str, network: Network)[source]

Bases: object

A bitcoin address

classmethod from_script(script: Script, network: Network)[source]

Parse a script as an address for the given network

is_valid_for_network(network: Network) bool[source]

Is the address valid for the provided network

script_pubkey() Script[source]

Return the scriptPubKey underlying an address.

to_address_data() AddressData[source]

Return the data for the address.

to_qr_uri() str[source]

Return a BIP-21 URI string for this address.

class bdkpython.bdk.AddressData[source]

Bases: object

The type of address.

P2PKH[source]

alias of P2PKH

P2SH[source]

alias of P2SH

SEGWIT[source]

alias of SEGWIT

is_P2PKH() bool[source]
is_P2SH() bool[source]
is_SEGWIT() bool[source]
is_p2pkh() bool[source]
is_p2sh() bool[source]
is_segwit() bool[source]
class bdkpython.bdk.AddressInfo(*, index: int, address: Address, keychain: KeychainKind)[source]

Bases: object

A derived address and the index it was found at.

address: Address

The address

index: int

Child index of this address

keychain: KeychainKind

Type of keychain

class bdkpython.bdk.AddressParseError[source]

Bases: Exception

exception Base58[source]

Bases: AddressParseError

exception Bech32[source]

Bases: AddressParseError

exception InvalidBase58PayloadLength[source]

Bases: AddressParseError

exception InvalidLegacyPrefix[source]

Bases: AddressParseError

exception LegacyAddressTooLong[source]

Bases: AddressParseError

exception NetworkValidation[source]

Bases: AddressParseError

exception OtherAddressParseErr[source]

Bases: AddressParseError

exception UnknownHrp[source]

Bases: AddressParseError

exception WitnessProgram(error_message)[source]

Bases: AddressParseError

exception WitnessVersion(error_message)[source]

Bases: AddressParseError

class bdkpython.bdk.AddressProtocol(*args, **kwargs)[source]

Bases: Protocol

A bitcoin address

is_valid_for_network(network: Network)[source]

Is the address valid for the provided network

script_pubkey()[source]

Return the scriptPubKey underlying an address.

to_address_data()[source]

Return the data for the address.

to_qr_uri()[source]

Return a BIP-21 URI string for this address.

class bdkpython.bdk.Amount(*args, **kwargs)[source]

Bases: object

The Amount type can be used to express Bitcoin amounts that support arithmetic and conversion to various denominations. The operations that Amount implements will panic when overflow or underflow occurs. Also note that since the internal representation of amounts is unsigned, subtracting below zero is considered an underflow and will cause a panic.

classmethod from_btc(btc: float)[source]

Convert from a value expressing bitcoins to an Amount.

classmethod from_sat(satoshi: int)[source]

Create an Amount with satoshi precision and the given number of satoshis.

to_btc() float[source]

Express this Amount as a floating-point value in Bitcoin. Please be aware of the risk of using floating-point numbers.

to_sat() int[source]

Get the number of satoshis in this Amount.

class bdkpython.bdk.AmountProtocol(*args, **kwargs)[source]

Bases: Protocol

The Amount type can be used to express Bitcoin amounts that support arithmetic and conversion to various denominations. The operations that Amount implements will panic when overflow or underflow occurs. Also note that since the internal representation of amounts is unsigned, subtracting below zero is considered an underflow and will cause a panic.

to_btc()[source]

Express this Amount as a floating-point value in Bitcoin. Please be aware of the risk of using floating-point numbers.

to_sat()[source]

Get the number of satoshis in this Amount.

class bdkpython.bdk.Anchor(*, confirmation_block_time: ConfirmationBlockTime, txid: Txid)[source]

Bases: object

confirmation_block_time: ConfirmationBlockTime
txid: Txid
class bdkpython.bdk.Balance(*, immature: Amount, trusted_pending: Amount, untrusted_pending: Amount, confirmed: Amount, trusted_spendable: Amount, total: Amount)[source]

Bases: object

Balance, differentiated into various categories.

confirmed: Amount

Confirmed and immediately spendable balance

immature: Amount

All coinbase outputs not yet matured

total: Amount

Get the whole balance visible to the wallet.

trusted_pending: Amount

Unconfirmed UTXOs generated by a wallet tx

trusted_spendable: Amount

Get sum of trusted_pending and confirmed coins.

This is the balance you can spend right now that shouldn’t get cancelled via another party double spending it.

untrusted_pending: Amount

Unconfirmed UTXOs received from an external wallet

class bdkpython.bdk.Bip32Error[source]

Bases: Exception

exception Base58(error_message)[source]

Bases: Bip32Error

exception CannotDeriveFromHardenedKey[source]

Bases: Bip32Error

exception Hex(error_message)[source]

Bases: Bip32Error

exception InvalidChildNumber(child_number)[source]

Bases: Bip32Error

exception InvalidChildNumberFormat[source]

Bases: Bip32Error

exception InvalidDerivationPathFormat[source]

Bases: Bip32Error

exception InvalidPublicKeyHexLength(length)[source]

Bases: Bip32Error

exception Secp256k1(error_message)[source]

Bases: Bip32Error

exception UnknownError(error_message)[source]

Bases: Bip32Error

exception UnknownVersion(version)[source]

Bases: Bip32Error

exception WrongExtendedKeyLength(length)[source]

Bases: Bip32Error

class bdkpython.bdk.Bip39Error[source]

Bases: Exception

exception AmbiguousLanguages(languages)[source]

Bases: Bip39Error

exception BadEntropyBitCount(bit_count)[source]

Bases: Bip39Error

exception BadWordCount(word_count)[source]

Bases: Bip39Error

exception InvalidChecksum[source]

Bases: Bip39Error

exception UnknownWord(index)[source]

Bases: Bip39Error

class bdkpython.bdk.BlockHash(*args, **kwargs)[source]

Bases: object

A bitcoin Block hash

classmethod from_bytes(bytes: bytes)[source]

Construct a hash-like type from 32 bytes.

classmethod from_string(hex: str)[source]

Construct a hash-like type from a hex string.

serialize() bytes[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.BlockHashProtocol(*args, **kwargs)[source]

Bases: Protocol

A bitcoin Block hash

serialize()[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.BlockId(*, height: int, hash: BlockHash)[source]

Bases: object

A reference to a block in the canonical chain.

hash: BlockHash

The hash of the block.

height: int

The height of the block.

class bdkpython.bdk.BumpFeeTxBuilder(txid: Txid, fee_rate: FeeRate)[source]

Bases: object

A BumpFeeTxBuilder is created by calling build_fee_bump on a wallet. After assigning it, you set options on it until finally calling finish to consume the builder and generate the transaction.

allow_dust(allow_dust: bool) BumpFeeTxBuilder[source]

Set whether the dust limit is checked.

Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.

current_height(height: int) BumpFeeTxBuilder[source]

Set the current blockchain height.

This will be used to:

1. Set the nLockTime for preventing fee sniping. Note: This will be ignored if you manually specify a nlocktime using TxBuilder::nlocktime.

2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at current_height, we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs, manually add them using TxBuilder::add_utxos. In both cases, if you don’t provide a current height, we use the last sync height.

finish(wallet: Wallet) Psbt[source]

Finish building the transaction.

Uses the thread-local random number generator (rng).

Returns a new Psbt per BIP174.

WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See Wallet::reveal_next_address.

nlocktime(locktime: LockTime) BumpFeeTxBuilder[source]

Use a specific nLockTime while creating the transaction.

This can cause conflicts if the wallet’s descriptors contain an “after” (OP_CLTV) operator.

set_exact_sequence(nsequence: int) BumpFeeTxBuilder[source]

Set an exact nSequence value.

This can cause conflicts if the wallet’s descriptors contain an “older” (OP_CSV) operator and the given nsequence is lower than the CSV value.

version(version: int) BumpFeeTxBuilder[source]

Build a transaction with a specific version.

The version should always be greater than 0 and greater than 1 if the wallet’s descriptors contain an “older” (OP_CSV) operator.

class bdkpython.bdk.BumpFeeTxBuilderProtocol(*args, **kwargs)[source]

Bases: Protocol

A BumpFeeTxBuilder is created by calling build_fee_bump on a wallet. After assigning it, you set options on it until finally calling finish to consume the builder and generate the transaction.

allow_dust(allow_dust: bool)[source]

Set whether the dust limit is checked.

Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.

current_height(height: int)[source]

Set the current blockchain height.

This will be used to:

1. Set the nLockTime for preventing fee sniping. Note: This will be ignored if you manually specify a nlocktime using TxBuilder::nlocktime.

2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at current_height, we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs, manually add them using TxBuilder::add_utxos. In both cases, if you don’t provide a current height, we use the last sync height.

finish(wallet: Wallet)[source]

Finish building the transaction.

Uses the thread-local random number generator (rng).

Returns a new Psbt per BIP174.

WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See Wallet::reveal_next_address.

nlocktime(locktime: LockTime)[source]

Use a specific nLockTime while creating the transaction.

This can cause conflicts if the wallet’s descriptors contain an “after” (OP_CLTV) operator.

set_exact_sequence(nsequence: int)[source]

Set an exact nSequence value.

This can cause conflicts if the wallet’s descriptors contain an “older” (OP_CSV) operator and the given nsequence is lower than the CSV value.

version(version: int)[source]

Build a transaction with a specific version.

The version should always be greater than 0 and greater than 1 if the wallet’s descriptors contain an “older” (OP_CSV) operator.

class bdkpython.bdk.CalculateFeeError[source]

Bases: Exception

exception MissingTxOut(out_points)[source]

Bases: CalculateFeeError

exception NegativeFee(amount)[source]

Bases: CalculateFeeError

class bdkpython.bdk.CannotConnectError[source]

Bases: Exception

exception Include(height)[source]

Bases: CannotConnectError

class bdkpython.bdk.CanonicalTx(*, transaction: Transaction, chain_position: ChainPosition)[source]

Bases: object

A transaction that is deemed to be part of the canonical history.

chain_position: ChainPosition

How the transaction is observed in the canonical chain (confirmed or unconfirmed).

transaction: Transaction

The transaction.

class bdkpython.bdk.CbfBuilder[source]

Bases: object

Build a BIP 157/158 light client to fetch transactions for a Wallet.

Options: * List of Peer: Bitcoin full-nodes for the light client to connect to. May be empty. * connections: The number of connections for the light client to maintain. * scan_type: Sync, recover, or start a new wallet. For more information see [ScanType]. * data_dir: Optional directory to store block headers and peers.

A note on recovering wallets. Developers should allow users to provide an approximate recovery height and an estimated number of transactions for the wallet. When determining how many scripts to check filters for, the Wallet lookahead value will be used. To ensure all transactions are recovered, the lookahead should be roughly the number of transactions in the wallet history.

build(wallet: Wallet) CbfComponents[source]

Construct a [CbfComponents] for a [Wallet].

configure_timeout_millis(handshake: int, response: int) CbfBuilder[source]

Configure the time in milliseconds that a node has to: 1. Respond to the initial connection 2. Respond to a request

connections(connections: int) CbfBuilder[source]

The number of connections for the light client to maintain. Default is two.

data_dir(data_dir: str) CbfBuilder[source]

Directory to store block headers and peers. If none is provided, the current working directory will be used.

peers(peers: List[Peer]) CbfBuilder[source]

Bitcoin full-nodes to attempt a connection with.

scan_type(scan_type: ScanType) CbfBuilder[source]

Select between syncing, recovering, or scanning for new wallets.

socks5_proxy(proxy: Socks5Proxy) CbfBuilder[source]

Configure connections to be established through a Socks5 proxy. The vast majority of the time, the connection is to a local Tor daemon, which is typically exposed at `127.0.0.1:9050.

class bdkpython.bdk.CbfBuilderProtocol(*args, **kwargs)[source]

Bases: Protocol

Build a BIP 157/158 light client to fetch transactions for a Wallet.

Options: * List of Peer: Bitcoin full-nodes for the light client to connect to. May be empty. * connections: The number of connections for the light client to maintain. * scan_type: Sync, recover, or start a new wallet. For more information see [ScanType]. * data_dir: Optional directory to store block headers and peers.

A note on recovering wallets. Developers should allow users to provide an approximate recovery height and an estimated number of transactions for the wallet. When determining how many scripts to check filters for, the Wallet lookahead value will be used. To ensure all transactions are recovered, the lookahead should be roughly the number of transactions in the wallet history.

build(wallet: Wallet)[source]

Construct a [CbfComponents] for a [Wallet].

configure_timeout_millis(handshake: int, response: int)[source]

Configure the time in milliseconds that a node has to: 1. Respond to the initial connection 2. Respond to a request

connections(connections: int)[source]

The number of connections for the light client to maintain. Default is two.

data_dir(data_dir: str)[source]

Directory to store block headers and peers. If none is provided, the current working directory will be used.

peers(peers: List[Peer])[source]

Bitcoin full-nodes to attempt a connection with.

scan_type(scan_type: ScanType)[source]

Select between syncing, recovering, or scanning for new wallets.

socks5_proxy(proxy: Socks5Proxy)[source]

Configure connections to be established through a Socks5 proxy. The vast majority of the time, the connection is to a local Tor daemon, which is typically exposed at `127.0.0.1:9050.

class bdkpython.bdk.CbfClient(*args, **kwargs)[source]

Bases: object

A [CbfClient] handles wallet updates from a [CbfNode].

async average_fee_rate(blockhash: BlockHash) FeeRate[source]

Fetch the average fee rate for a block by requesting it from a peer. Not recommend for resource-limited devices.

async broadcast(transaction: Transaction) Wtxid[source]

Broadcast a transaction to the network, erroring if the node has stopped running.

connect(peer: Peer) None[source]

Add another [Peer] to attempt a connection with.

is_running() bool[source]

Check if the node is still running in the background.

lookup_host(hostname: str) List[IpAddress][source]

Query a Bitcoin DNS seeder using the configured resolver.

This is not a generic DNS implementation. Host names are prefixed with a x849 to filter for compact block filter nodes from the seeder. For example dns.myseeder.com will be queried as x849.dns.myseeder.com. This has no guarantee to return any IpAddr.

async min_broadcast_feerate() FeeRate[source]

The minimum fee rate required to broadcast a transcation to all connected peers.

async next_info() Info[source]

Return the next available info message from a node. If none is returned, the node has stopped.

async next_warning() Warning[source]

Return the next available warning message from a node. If none is returned, the node has stopped.

shutdown() None[source]

Stop the [CbfNode]. Errors if the node is already stopped.

async update() Update[source]

Return an [Update]. This is method returns once the node syncs to the rest of the network or a new block has been gossiped.

class bdkpython.bdk.CbfClientProtocol(*args, **kwargs)[source]

Bases: Protocol

A [CbfClient] handles wallet updates from a [CbfNode].

average_fee_rate(blockhash: BlockHash)[source]

Fetch the average fee rate for a block by requesting it from a peer. Not recommend for resource-limited devices.

broadcast(transaction: Transaction)[source]

Broadcast a transaction to the network, erroring if the node has stopped running.

connect(peer: Peer)[source]

Add another [Peer] to attempt a connection with.

is_running()[source]

Check if the node is still running in the background.

lookup_host(hostname: str)[source]

Query a Bitcoin DNS seeder using the configured resolver.

This is not a generic DNS implementation. Host names are prefixed with a x849 to filter for compact block filter nodes from the seeder. For example dns.myseeder.com will be queried as x849.dns.myseeder.com. This has no guarantee to return any IpAddr.

min_broadcast_feerate()[source]

The minimum fee rate required to broadcast a transcation to all connected peers.

next_info()[source]

Return the next available info message from a node. If none is returned, the node has stopped.

next_warning()[source]

Return the next available warning message from a node. If none is returned, the node has stopped.

shutdown()[source]

Stop the [CbfNode]. Errors if the node is already stopped.

update()[source]

Return an [Update]. This is method returns once the node syncs to the rest of the network or a new block has been gossiped.

class bdkpython.bdk.CbfComponents(*, client: CbfClient, node: CbfNode)[source]

Bases: object

Receive a [CbfClient] and [CbfNode].

client: CbfClient

Publish events to the node, like broadcasting transactions or adding scripts.

node: CbfNode

The node to run and fetch transactions for a [Wallet].

class bdkpython.bdk.CbfError[source]

Bases: Exception

exception NodeStopped[source]

Bases: CbfError

class bdkpython.bdk.CbfNode(*args, **kwargs)[source]

Bases: object

A [CbfNode] gathers transactions for a [Wallet]. To receive [Update] for [Wallet], refer to the [CbfClient]. The [CbfNode] will run until instructed to stop.

run() None[source]

Start the node on a detached OS thread and immediately return.

class bdkpython.bdk.CbfNodeProtocol(*args, **kwargs)[source]

Bases: Protocol

A [CbfNode] gathers transactions for a [Wallet]. To receive [Update] for [Wallet], refer to the [CbfClient]. The [CbfNode] will run until instructed to stop.

run()[source]

Start the node on a detached OS thread and immediately return.

class bdkpython.bdk.ChainChange(*, height: int, hash: BlockHash | None)[source]

Bases: object

The hash added or removed at the given height.

hash: BlockHash | None

A hash was added or must be removed.

height: int

Effected height

class bdkpython.bdk.ChainPosition[source]

Bases: object

Represents the observed position of some chain data.

CONFIRMED[source]

alias of CONFIRMED

UNCONFIRMED[source]

alias of UNCONFIRMED

is_CONFIRMED() bool[source]
is_UNCONFIRMED() bool[source]
is_confirmed() bool[source]
is_unconfirmed() bool[source]
class bdkpython.bdk.ChangeSet[source]

Bases: object

change_descriptor() Descriptor | None[source]

Get the change Descriptor

descriptor() Descriptor | None[source]

Get the receiving Descriptor.

classmethod from_aggregate(descriptor: Descriptor | None, change_descriptor: Descriptor | None, network: Network | None, local_chain: LocalChainChangeSet, tx_graph: TxGraphChangeSet, indexer: IndexerChangeSet)[source]
classmethod from_descriptor_and_network(descriptor: Descriptor | None, change_descriptor: Descriptor | None, network: Network | None)[source]
classmethod from_indexer_changeset(indexer_changes: IndexerChangeSet)[source]

Start a wallet ChangeSet from indexer changes.

classmethod from_local_chain_changes(local_chain_changes: LocalChainChangeSet)[source]

Start a wallet ChangeSet from local chain changes.

classmethod from_merge(left: ChangeSet, right: ChangeSet)[source]

Build a ChangeSet by merging together two ChangeSet.

classmethod from_tx_graph_changeset(tx_graph_changeset: TxGraphChangeSet)[source]

Start a wallet ChangeSet from transaction graph changes.

indexer_changeset() IndexerChangeSet[source]

Get the changes to the indexer.

localchain_changeset() LocalChainChangeSet[source]

Get the changes to the local chain.

network() Network | None[source]

Get the Network

tx_graph_changeset() TxGraphChangeSet[source]

Get the changes to the transaction graph.

class bdkpython.bdk.ChangeSetProtocol(*args, **kwargs)[source]

Bases: Protocol

change_descriptor()[source]

Get the change Descriptor

descriptor()[source]

Get the receiving Descriptor.

indexer_changeset()[source]

Get the changes to the indexer.

localchain_changeset()[source]

Get the changes to the local chain.

network()[source]

Get the Network

tx_graph_changeset()[source]

Get the changes to the transaction graph.

class bdkpython.bdk.ChangeSpendPolicy(*values)[source]

Bases: Enum

Policy regarding the use of change outputs when creating a transaction.

CHANGE_ALLOWED = 0

Use both change and non-change outputs (default).

CHANGE_FORBIDDEN = 2

Only use non-change outputs (see [bdk_wallet::TxBuilder::do_not_spend_change]).

ONLY_CHANGE = 1

Only use change outputs (see [bdk_wallet::TxBuilder::only_spend_change]).

class bdkpython.bdk.Condition(*, csv: int | None, timelock: LockTime | None)[source]

Bases: object

An extra condition that must be satisfied but that is out of control of the user

csv: int | None

Optional CheckSequenceVerify condition

timelock: LockTime | None

Optional timelock condition

class bdkpython.bdk.ConfirmationBlockTime(*, block_id: BlockId, confirmation_time: int)[source]

Bases: object

Represents the confirmation block and time of a transaction.

block_id: BlockId

The anchor block.

confirmation_time: int

The confirmation time of the transaction being anchored.

class bdkpython.bdk.ControlBlock(*, internal_key: bytes, merkle_branch: List[str], output_key_parity: int, leaf_version: int)[source]

Bases: object

internal_key: bytes

The internal key.

leaf_version: int

The tapleaf version.

merkle_branch: List[str]

The merkle proof of a script associated with this leaf.

output_key_parity: int

The parity of the output key (NOT THE INTERNAL KEY WHICH IS ALWAYS XONLY).

class bdkpython.bdk.CreateTxError[source]

Bases: Exception

exception ChangePolicyDescriptor[source]

Bases: CreateTxError

exception CoinSelection(error_message)[source]

Bases: CreateTxError

exception Descriptor(error_message)[source]

Bases: CreateTxError

exception FeeRateTooLow(required)[source]

Bases: CreateTxError

exception FeeTooLow(required)[source]

Bases: CreateTxError

exception InsufficientFunds(needed, available)[source]

Bases: CreateTxError

exception LockTime(requested, required)[source]

Bases: CreateTxError

exception LockTimeConversionError[source]

Bases: CreateTxError

exception MiniscriptPsbt(error_message)[source]

Bases: CreateTxError

exception MissingKeyOrigin(key)[source]

Bases: CreateTxError

exception MissingNonWitnessUtxo(outpoint)[source]

Bases: CreateTxError

exception NoRecipients[source]

Bases: CreateTxError

exception NoUtxosSelected[source]

Bases: CreateTxError

exception OutputBelowDustLimit(index)[source]

Bases: CreateTxError

exception Policy(error_message)[source]

Bases: CreateTxError

exception Psbt(error_message)[source]

Bases: CreateTxError

exception PushBytesError[source]

Bases: CreateTxError

exception RbfSequenceCsv(sequence, csv)[source]

Bases: CreateTxError

exception SpendingPolicyRequired(kind)[source]

Bases: CreateTxError

exception UnknownUtxo(outpoint)[source]

Bases: CreateTxError

exception Version0[source]

Bases: CreateTxError

exception Version1Csv[source]

Bases: CreateTxError

class bdkpython.bdk.CreateWithPersistError[source]

Bases: Exception

exception DataAlreadyExists[source]

Bases: CreateWithPersistError

exception Descriptor(error_message)[source]

Bases: CreateWithPersistError

exception Persist(error_message)[source]

Bases: CreateWithPersistError

class bdkpython.bdk.DerivationPath(path: str)[source]

Bases: object

A BIP-32 derivation path.

is_empty() bool[source]

Returns true if the derivation path is empty

is_master() bool[source]

Returns whether derivation path represents master key (i.e. it’s length is empty). True for m path.

len() int[source]

Returns length of the derivation path

classmethod master()[source]

Returns derivation path for a master key (i.e. empty derivation path)

class bdkpython.bdk.DerivationPathProtocol(*args, **kwargs)[source]

Bases: Protocol

A BIP-32 derivation path.

is_empty()[source]

Returns true if the derivation path is empty

is_master()[source]

Returns whether derivation path represents master key (i.e. it’s length is empty). True for m path.

len()[source]

Returns length of the derivation path

class bdkpython.bdk.Descriptor(descriptor: str, network: Network)[source]

Bases: object

An expression of how to derive output scripts: https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md

desc_type() DescriptorType[source]
descriptor_id() DescriptorId[source]

A unique identifier for the descriptor.

is_multipath() bool[source]

Does this descriptor contain paths: https://github.com/bitcoin/bips/blob/master/bip-0389.mediawiki

max_weight_to_satisfy() int[source]

Computes an upper bound on the difference between a non-satisfied TxIn’s segwit_weight and a satisfied TxIn’s segwit_weight.

classmethod new_bip44(secret_key: DescriptorSecretKey, keychain_kind: KeychainKind, network: Network)[source]

Multi-account hierarchy descriptor: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki

classmethod new_bip44_public(public_key: DescriptorPublicKey, fingerprint: str, keychain_kind: KeychainKind, network: Network)[source]

Multi-account hierarchy descriptor: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki

classmethod new_bip49(secret_key: DescriptorSecretKey, keychain_kind: KeychainKind, network: Network)[source]

P2SH nested P2WSH descriptor: https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki

classmethod new_bip49_public(public_key: DescriptorPublicKey, fingerprint: str, keychain_kind: KeychainKind, network: Network)[source]

P2SH nested P2WSH descriptor: https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki

classmethod new_bip84(secret_key: DescriptorSecretKey, keychain_kind: KeychainKind, network: Network)[source]

Pay to witness PKH descriptor: https://github.com/bitcoin/bips/blob/master/bip-0084.mediawiki

classmethod new_bip84_public(public_key: DescriptorPublicKey, fingerprint: str, keychain_kind: KeychainKind, network: Network)[source]

Pay to witness PKH descriptor: https://github.com/bitcoin/bips/blob/master/bip-0084.mediawiki

classmethod new_bip86(secret_key: DescriptorSecretKey, keychain_kind: KeychainKind, network: Network)[source]

Single key P2TR descriptor: https://github.com/bitcoin/bips/blob/master/bip-0086.mediawiki

classmethod new_bip86_public(public_key: DescriptorPublicKey, fingerprint: str, keychain_kind: KeychainKind, network: Network)[source]

Single key P2TR descriptor: https://github.com/bitcoin/bips/blob/master/bip-0086.mediawiki

to_single_descriptors() List[Descriptor][source]

Return descriptors for all valid paths.

to_string_with_secret() str[source]

Dangerously convert the descriptor to a string.

class bdkpython.bdk.DescriptorError[source]

Bases: Exception

exception Base58(error_message)[source]

Bases: DescriptorError

exception Bip32(error_message)[source]

Bases: DescriptorError

exception ExternalAndInternalAreTheSame[source]

Bases: DescriptorError

exception HardenedDerivationXpub[source]

Bases: DescriptorError

exception Hex(error_message)[source]

Bases: DescriptorError

exception InvalidDescriptorCharacter(char)[source]

Bases: DescriptorError

exception InvalidDescriptorChecksum[source]

Bases: DescriptorError

exception InvalidHdKeyPath[source]

Bases: DescriptorError

exception Key(error_message)[source]

Bases: DescriptorError

exception Miniscript(error_message)[source]

Bases: DescriptorError

exception MultiPath[source]

Bases: DescriptorError

exception Pk(error_message)[source]

Bases: DescriptorError

exception Policy(error_message)[source]

Bases: DescriptorError

class bdkpython.bdk.DescriptorId(*args, **kwargs)[source]

Bases: object

A collision-proof unique identifier for a descriptor.

classmethod from_bytes(bytes: bytes)[source]

Construct a hash-like type from 32 bytes.

classmethod from_string(hex: str)[source]

Construct a hash-like type from a hex string.

serialize() bytes[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.DescriptorIdProtocol(*args, **kwargs)[source]

Bases: Protocol

A collision-proof unique identifier for a descriptor.

serialize()[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.DescriptorKeyError[source]

Bases: Exception

exception Bip32(error_message)[source]

Bases: DescriptorKeyError

exception InvalidKeyType[source]

Bases: DescriptorKeyError

exception Parse(error_message)[source]

Bases: DescriptorKeyError

class bdkpython.bdk.DescriptorProtocol(*args, **kwargs)[source]

Bases: Protocol

An expression of how to derive output scripts: https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md

desc_type()[source]
descriptor_id()[source]

A unique identifier for the descriptor.

is_multipath()[source]

Does this descriptor contain paths: https://github.com/bitcoin/bips/blob/master/bip-0389.mediawiki

max_weight_to_satisfy()[source]

Computes an upper bound on the difference between a non-satisfied TxIn’s segwit_weight and a satisfied TxIn’s segwit_weight.

to_single_descriptors()[source]

Return descriptors for all valid paths.

to_string_with_secret()[source]

Dangerously convert the descriptor to a string.

class bdkpython.bdk.DescriptorPublicKey(*args, **kwargs)[source]

Bases: object

A descriptor public key.

derive(path: DerivationPath) DescriptorPublicKey[source]

Derive the descriptor public key at the given derivation path.

extend(path: DerivationPath) DescriptorPublicKey[source]

Extend the descriptor public key by the given derivation path.

classmethod from_string(public_key: str)[source]

Attempt to parse a string as a descriptor public key.

is_multipath() bool[source]

Whether or not this key has multiple derivation paths.

master_fingerprint() str[source]

The fingerprint of the master key associated with this key, 0x00000000 if none.

class bdkpython.bdk.DescriptorPublicKeyProtocol(*args, **kwargs)[source]

Bases: Protocol

A descriptor public key.

derive(path: DerivationPath)[source]

Derive the descriptor public key at the given derivation path.

extend(path: DerivationPath)[source]

Extend the descriptor public key by the given derivation path.

is_multipath()[source]

Whether or not this key has multiple derivation paths.

master_fingerprint()[source]

The fingerprint of the master key associated with this key, 0x00000000 if none.

class bdkpython.bdk.DescriptorSecretKey(network: Network, mnemonic: Mnemonic, password: str | None)[source]

Bases: object

A descriptor containing secret data.

as_public() DescriptorPublicKey[source]

Return the descriptor public key corresponding to this secret.

derive(path: DerivationPath) DescriptorSecretKey[source]

Derive a descriptor secret key at a given derivation path.

extend(path: DerivationPath) DescriptorSecretKey[source]

Extend the descriptor secret key by the derivation path.

classmethod from_string(private_key: str)[source]

Attempt to parse a string as a descriptor secret key.

secret_bytes() bytes[source]

Return the bytes of this descriptor secret key.

class bdkpython.bdk.DescriptorSecretKeyProtocol(*args, **kwargs)[source]

Bases: Protocol

A descriptor containing secret data.

as_public()[source]

Return the descriptor public key corresponding to this secret.

derive(path: DerivationPath)[source]

Derive a descriptor secret key at a given derivation path.

extend(path: DerivationPath)[source]

Extend the descriptor secret key by the derivation path.

secret_bytes()[source]

Return the bytes of this descriptor secret key.

class bdkpython.bdk.DescriptorType(*values)[source]

Bases: Enum

Descriptor Type of the descriptor

BARE = 0

Bare descriptor(Contains the native P2pk)

PKH = 2

Pkh Descriptor

SH = 1

Pure Sh Descriptor. Does not contain nested Wsh/Wpkh

SH_SORTED_MULTI = 7

Sh Sorted Multi

SH_WPKH = 6

Sh wrapped Wpkh

SH_WSH = 5

Sh Wrapped Wsh

SH_WSH_SORTED_MULTI = 9

Sh Wsh Sorted Multi

TR = 10

Tr Descriptor

WPKH = 3

Wpkh Descriptor

WSH = 4

Wsh

WSH_SORTED_MULTI = 8

Wsh Sorted Multi

class bdkpython.bdk.ElectrumClient(url: str, socks5: object | str | None = <object object>)[source]

Bases: object

Wrapper around an electrum_client::ElectrumApi which includes an internal in-memory transaction cache to avoid re-fetching already downloaded transactions.

block_headers_subscribe() HeaderNotification[source]

Subscribes to notifications for new block headers, by sending a blockchain.headers.subscribe call.

estimate_fee(number: int) float[source]

Estimates the fee required in bitcoin per kilobyte to confirm a transaction in number blocks.

full_scan(request: FullScanRequest, stop_gap: int, batch_size: int, fetch_prev_txouts: bool) Update[source]

Full scan the keychain scripts specified with the blockchain (via an Electrum client) and returns updates for bdk_chain data structures.

  • request: struct with data required to perform a spk-based blockchain client

full scan, see FullScanRequest. - stop_gap: the full scan for each keychain stops after a gap of script pubkeys with no associated transactions. - batch_size: specifies the max number of script pubkeys to request for in a single batch request. - fetch_prev_txouts: specifies whether we want previous TxOuts for fee calculation. Note that this requires additional calls to the Electrum server, but is necessary for calculating the fee on a transaction if your wallet does not own the inputs. Methods like Wallet.calculate_fee and Wallet.calculate_fee_rate will return a CalculateFeeError::MissingTxOut error if those TxOuts are not present in the transaction graph.

ping() None[source]

Pings the server.

server_features() ServerFeaturesRes[source]

Returns the capabilities of the server.

sync(request: SyncRequest, batch_size: int, fetch_prev_txouts: bool) Update[source]

Sync a set of scripts with the blockchain (via an Electrum client) for the data specified and returns updates for bdk_chain data structures.

  • request: struct with data required to perform a spk-based blockchain client

sync, see SyncRequest. - batch_size: specifies the max number of script pubkeys to request for in a single batch request. - fetch_prev_txouts: specifies whether we want previous TxOuts for fee calculation. Note that this requires additional calls to the Electrum server, but is necessary for calculating the fee on a transaction if your wallet does not own the inputs. Methods like Wallet.calculate_fee and Wallet.calculate_fee_rate will return a CalculateFeeError::MissingTxOut error if those TxOuts are not present in the transaction graph.

If the scripts to sync are unknown, such as when restoring or importing a keychain that may include scripts that have been used, use full_scan with the keychain.

transaction_broadcast(tx: Transaction) Txid[source]

Broadcasts a transaction to the network.

class bdkpython.bdk.ElectrumClientProtocol(*args, **kwargs)[source]

Bases: Protocol

Wrapper around an electrum_client::ElectrumApi which includes an internal in-memory transaction cache to avoid re-fetching already downloaded transactions.

block_headers_subscribe()[source]

Subscribes to notifications for new block headers, by sending a blockchain.headers.subscribe call.

estimate_fee(number: int)[source]

Estimates the fee required in bitcoin per kilobyte to confirm a transaction in number blocks.

full_scan(request: FullScanRequest, stop_gap: int, batch_size: int, fetch_prev_txouts: bool)[source]

Full scan the keychain scripts specified with the blockchain (via an Electrum client) and returns updates for bdk_chain data structures.

  • request: struct with data required to perform a spk-based blockchain client

full scan, see FullScanRequest. - stop_gap: the full scan for each keychain stops after a gap of script pubkeys with no associated transactions. - batch_size: specifies the max number of script pubkeys to request for in a single batch request. - fetch_prev_txouts: specifies whether we want previous TxOuts for fee calculation. Note that this requires additional calls to the Electrum server, but is necessary for calculating the fee on a transaction if your wallet does not own the inputs. Methods like Wallet.calculate_fee and Wallet.calculate_fee_rate will return a CalculateFeeError::MissingTxOut error if those TxOuts are not present in the transaction graph.

ping()[source]

Pings the server.

server_features()[source]

Returns the capabilities of the server.

sync(request: SyncRequest, batch_size: int, fetch_prev_txouts: bool)[source]

Sync a set of scripts with the blockchain (via an Electrum client) for the data specified and returns updates for bdk_chain data structures.

  • request: struct with data required to perform a spk-based blockchain client

sync, see SyncRequest. - batch_size: specifies the max number of script pubkeys to request for in a single batch request. - fetch_prev_txouts: specifies whether we want previous TxOuts for fee calculation. Note that this requires additional calls to the Electrum server, but is necessary for calculating the fee on a transaction if your wallet does not own the inputs. Methods like Wallet.calculate_fee and Wallet.calculate_fee_rate will return a CalculateFeeError::MissingTxOut error if those TxOuts are not present in the transaction graph.

If the scripts to sync are unknown, such as when restoring or importing a keychain that may include scripts that have been used, use full_scan with the keychain.

transaction_broadcast(tx: Transaction)[source]

Broadcasts a transaction to the network.

class bdkpython.bdk.ElectrumError[source]

Bases: Exception

exception AllAttemptsErrored[source]

Bases: ElectrumError

exception AlreadySubscribed[source]

Bases: ElectrumError

exception Bitcoin(error_message)[source]

Bases: ElectrumError

exception CouldNotCreateConnection(error_message)[source]

Bases: ElectrumError

exception CouldntLockReader[source]

Bases: ElectrumError

exception Hex(error_message)[source]

Bases: ElectrumError

exception InvalidDnsNameError(domain)[source]

Bases: ElectrumError

exception InvalidResponse(error_message)[source]

Bases: ElectrumError

exception IoError(error_message)[source]

Bases: ElectrumError

exception Json(error_message)[source]

Bases: ElectrumError

exception Message(error_message)[source]

Bases: ElectrumError

exception MissingDomain[source]

Bases: ElectrumError

exception Mpsc[source]

Bases: ElectrumError

exception NotSubscribed[source]

Bases: ElectrumError

exception Protocol(error_message)[source]

Bases: ElectrumError

exception RequestAlreadyConsumed[source]

Bases: ElectrumError

exception SharedIoError(error_message)[source]

Bases: ElectrumError

class bdkpython.bdk.EsploraClient(url: str, proxy: object | str | None = <object object>)[source]

Bases: object

Wrapper around an esplora_client::BlockingClient which includes an internal in-memory transaction cache to avoid re-fetching already downloaded transactions.

broadcast(transaction: Transaction) None[source]

Broadcast a [Transaction] to Esplora.

full_scan(request: FullScanRequest, stop_gap: int, parallel_requests: int) Update[source]

Scan keychain scripts for transactions against Esplora, returning an update that can be applied to the receiving structures.

request provides the data required to perform a script-pubkey-based full scan (see [FullScanRequest]). The full scan for each keychain (K) stops after a gap of stop_gap script pubkeys with no associated transactions. parallel_requests specifies the maximum number of HTTP requests to make in parallel.

get_block_hash(block_height: int) BlockHash[source]

Get the [BlockHash] of a specific block height.

get_fee_estimates() dict[int, float][source]

Get a map where the key is the confirmation target (in number of blocks) and the value is the estimated feerate (in sat/vB).

get_height() int[source]

Get the height of the current blockchain tip.

get_tx(txid: Txid) Transaction | None[source]

Get a [Transaction] option given its [Txid].

get_tx_info(txid: Txid) Tx | None[source]

Get transaction info given its [Txid].

get_tx_status(txid: Txid) TxStatus[source]

Get the status of a [Transaction] given its [Txid].

sync(request: SyncRequest, parallel_requests: int) Update[source]

Sync a set of scripts, txids, and/or outpoints against Esplora.

request provides the data required to perform a script-pubkey-based sync (see [SyncRequest]). parallel_requests specifies the maximum number of HTTP requests to make in parallel.

class bdkpython.bdk.EsploraClientProtocol(*args, **kwargs)[source]

Bases: Protocol

Wrapper around an esplora_client::BlockingClient which includes an internal in-memory transaction cache to avoid re-fetching already downloaded transactions.

broadcast(transaction: Transaction)[source]

Broadcast a [Transaction] to Esplora.

full_scan(request: FullScanRequest, stop_gap: int, parallel_requests: int)[source]

Scan keychain scripts for transactions against Esplora, returning an update that can be applied to the receiving structures.

request provides the data required to perform a script-pubkey-based full scan (see [FullScanRequest]). The full scan for each keychain (K) stops after a gap of stop_gap script pubkeys with no associated transactions. parallel_requests specifies the maximum number of HTTP requests to make in parallel.

get_block_hash(block_height: int)[source]

Get the [BlockHash] of a specific block height.

get_fee_estimates()[source]

Get a map where the key is the confirmation target (in number of blocks) and the value is the estimated feerate (in sat/vB).

get_height()[source]

Get the height of the current blockchain tip.

get_tx(txid: Txid)[source]

Get a [Transaction] option given its [Txid].

get_tx_info(txid: Txid)[source]

Get transaction info given its [Txid].

get_tx_status(txid: Txid)[source]

Get the status of a [Transaction] given its [Txid].

sync(request: SyncRequest, parallel_requests: int)[source]

Sync a set of scripts, txids, and/or outpoints against Esplora.

request provides the data required to perform a script-pubkey-based sync (see [SyncRequest]). parallel_requests specifies the maximum number of HTTP requests to make in parallel.

class bdkpython.bdk.EsploraError[source]

Bases: Exception

exception BitcoinEncoding(error_message)[source]

Bases: EsploraError

exception HeaderHashNotFound[source]

Bases: EsploraError

exception HeaderHeightNotFound(height)[source]

Bases: EsploraError

exception HexToArray(error_message)[source]

Bases: EsploraError

exception HexToBytes(error_message)[source]

Bases: EsploraError

exception HttpResponse(status, error_message)[source]

Bases: EsploraError

exception InvalidHttpHeaderName(name)[source]

Bases: EsploraError

exception InvalidHttpHeaderValue(value)[source]

Bases: EsploraError

exception InvalidResponse[source]

Bases: EsploraError

exception Minreq(error_message)[source]

Bases: EsploraError

exception Parsing(error_message)[source]

Bases: EsploraError

exception RequestAlreadyConsumed[source]

Bases: EsploraError

exception StatusCode(error_message)[source]

Bases: EsploraError

exception TransactionNotFound[source]

Bases: EsploraError

class bdkpython.bdk.EvictedTx(*, txid: Txid, evicted_at: int)[source]

Bases: object

This type replaces the Rust tuple (txid, evicted_at) used in the Wallet::apply_evicted_txs` method, where evicted_at is the timestamp of when the transaction txid was evicted from the mempool. Transactions may be evicted for paying a low fee rate or having invalid scripts.

evicted_at: int
txid: Txid
class bdkpython.bdk.ExtractTxError[source]

Bases: Exception

exception AbsurdFeeRate(fee_rate)[source]

Bases: ExtractTxError

exception MissingInputValue[source]

Bases: ExtractTxError

exception OtherExtractTxErr[source]

Bases: ExtractTxError

exception SendingTooMuch[source]

Bases: ExtractTxError

class bdkpython.bdk.FeeRate(*args, **kwargs)[source]

Bases: object

Represents fee rate.

This is an integer type representing fee rate in sat/kwu. It provides protection against mixing up the types as well as basic formatting features.

classmethod from_sat_per_kwu(sat_kwu: int)[source]
classmethod from_sat_per_vb(sat_vb: int)[source]
to_sat_per_kwu() int[source]
to_sat_per_vb_ceil() int[source]
to_sat_per_vb_floor() int[source]
class bdkpython.bdk.FeeRateError[source]

Bases: Exception

exception ArithmeticOverflow[source]

Bases: FeeRateError

class bdkpython.bdk.FeeRateProtocol(*args, **kwargs)[source]

Bases: Protocol

Represents fee rate.

This is an integer type representing fee rate in sat/kwu. It provides protection against mixing up the types as well as basic formatting features.

to_sat_per_kwu()[source]
to_sat_per_vb_ceil()[source]
to_sat_per_vb_floor()[source]
class bdkpython.bdk.FinalizedPsbtResult(*, psbt: Psbt, could_finalize: bool, errors: List[PsbtFinalizeError] | None)[source]

Bases: object

could_finalize: bool
errors: List[PsbtFinalizeError] | None
psbt: Psbt
class bdkpython.bdk.FromScriptError[source]

Bases: Exception

exception OtherFromScriptErr[source]

Bases: FromScriptError

exception UnrecognizedScript[source]

Bases: FromScriptError

exception WitnessProgram(error_message)[source]

Bases: FromScriptError

exception WitnessVersion(error_message)[source]

Bases: FromScriptError

class bdkpython.bdk.FullScanRequest(*args, **kwargs)[source]

Bases: object

class bdkpython.bdk.FullScanRequestBuilder(*args, **kwargs)[source]

Bases: object

build() FullScanRequest[source]
inspect_spks_for_all_keychains(inspector: FullScanScriptInspector) FullScanRequestBuilder[source]
class bdkpython.bdk.FullScanRequestBuilderProtocol(*args, **kwargs)[source]

Bases: Protocol

build()[source]
inspect_spks_for_all_keychains(inspector: FullScanScriptInspector)[source]
class bdkpython.bdk.FullScanRequestProtocol(*args, **kwargs)[source]

Bases: Protocol

class bdkpython.bdk.FullScanScriptInspector[source]

Bases: object

inspect(keychain: KeychainKind, index: int, script: Script)[source]
class bdkpython.bdk.FullScanScriptInspectorImpl(*args, **kwargs)[source]

Bases: object

inspect(keychain: KeychainKind, index: int, script: Script) None[source]
class bdkpython.bdk.FullScanScriptInspectorProtocol(*args, **kwargs)[source]

Bases: Protocol

inspect(keychain: KeychainKind, index: int, script: Script)[source]
class bdkpython.bdk.HashParseError[source]

Bases: Exception

exception InvalidHash(len)[source]

Bases: HashParseError

exception InvalidHexString(hex)[source]

Bases: HashParseError

class bdkpython.bdk.HashableOutPoint(outpoint: OutPoint)[source]

Bases: object

An [OutPoint] used as a key in a hash map.

Due to limitations in generating the foreign language bindings, we cannot use [OutPoint] as a key for hash maps.

outpoint() OutPoint[source]

Get the internal [OutPoint]

class bdkpython.bdk.HashableOutPointProtocol(*args, **kwargs)[source]

Bases: Protocol

An [OutPoint] used as a key in a hash map.

Due to limitations in generating the foreign language bindings, we cannot use [OutPoint] as a key for hash maps.

outpoint()[source]

Get the internal [OutPoint]

class bdkpython.bdk.Header(*, version: int, prev_blockhash: BlockHash, merkle_root: TxMerkleNode, time: int, bits: int, nonce: int)[source]

Bases: object

Bitcoin block header. Contains all the block’s information except the actual transactions, but including a root of a merkle tree committing to all transactions in the block.

bits: int

The target value below which the blockhash must lie.

merkle_root: TxMerkleNode

The root hash of the merkle tree of transactions in the block.

nonce: int

The nonce, selected to obtain a low enough blockhash.

prev_blockhash: BlockHash

Reference to the previous block in the chain.

time: int

The timestamp of the block, as claimed by the miner.

version: int

Block version, now repurposed for soft fork signalling.

class bdkpython.bdk.HeaderNotification(*, height: int, header: Header)[source]

Bases: object

Notification of a new block header.

header: Header

Newly added header.

height: int

New block height.

class bdkpython.bdk.IndexerChangeSet(*, last_revealed: dict[DescriptorId, int])[source]

Bases: object

Mapping of descriptors to their last revealed index.

last_revealed: dict[DescriptorId, int]
class bdkpython.bdk.Info[source]

Bases: object

A log message from the node.

BLOCK_RECEIVED[source]

alias of BLOCK_RECEIVED

CONNECTIONS_MET[source]

alias of CONNECTIONS_MET

PROGRESS[source]

alias of PROGRESS

SUCCESSFUL_HANDSHAKE[source]

alias of SUCCESSFUL_HANDSHAKE

is_BLOCK_RECEIVED() bool[source]
is_CONNECTIONS_MET() bool[source]
is_PROGRESS() bool[source]
is_SUCCESSFUL_HANDSHAKE() bool[source]
is_block_received() bool[source]
is_connections_met() bool[source]
is_progress() bool[source]
is_successful_handshake() bool[source]
class bdkpython.bdk.Input(*, non_witness_utxo: Transaction | None, witness_utxo: TxOut | None, partial_sigs: dict[str, bytes], sighash_type: str | None, redeem_script: Script | None, witness_script: Script | None, bip32_derivation: dict[str, KeySource], final_script_sig: Script | None, final_script_witness: List[bytes] | None, ripemd160_preimages: dict[str, bytes], sha256_preimages: dict[str, bytes], hash160_preimages: dict[str, bytes], hash256_preimages: dict[str, bytes], tap_key_sig: bytes | None, tap_script_sigs: dict[TapScriptSigKey, bytes], tap_scripts: dict[ControlBlock, TapScriptEntry], tap_key_origins: dict[str, TapKeyOrigin], tap_internal_key: str | None, tap_merkle_root: str | None, proprietary: dict[ProprietaryKey, bytes], unknown: dict[Key, bytes])[source]

Bases: object

A key-value map for an input of the corresponding index in the unsigned transaction.

bip32_derivation: dict[str, KeySource]

A map from public keys needed to sign this input to their corresponding master key fingerprints and derivation paths.

final_script_sig: Script | None

The finalized, fully-constructed scriptSig with signatures and any other scripts necessary for this input to pass validation.

final_script_witness: List[bytes] | None

The finalized, fully-constructed scriptWitness with signatures and any other scripts necessary for this input to pass validation.

hash160_preimages: dict[str, bytes]

HASH160 hash to preimage map.

hash256_preimages: dict[str, bytes]

HASH256 hash to preimage map.

non_witness_utxo: Transaction | None

The non-witness transaction this input spends from. Should only be Option::Some for inputs which spend non-segwit outputs or if it is unknown whether an input spends a segwit output.

partial_sigs: dict[str, bytes]

A map from public keys to their corresponding signature as would be pushed to the stack from a scriptSig or witness for a non-taproot inputs.

proprietary: dict[ProprietaryKey, bytes]

Proprietary key-value pairs for this input.

redeem_script: Script | None

The redeem script for this input.

ripemd160_preimages: dict[str, bytes]

RIPEMD160 hash to preimage map.

sha256_preimages: dict[str, bytes]

SHA256 hash to preimage map.

sighash_type: str | None

The sighash type to be used for this input. Signatures for this input must use the sighash type.

tap_internal_key: str | None

Taproot Internal key.

tap_key_origins: dict[str, TapKeyOrigin]

Map of tap root x only keys to origin info and leaf hashes contained in it.

tap_key_sig: bytes | None

Serialized taproot signature with sighash type for key spend.

tap_merkle_root: str | None

Taproot Merkle root.

tap_script_sigs: dict[TapScriptSigKey, bytes]

Map of <xonlypubkey>|<leafhash> with signature.

tap_scripts: dict[ControlBlock, TapScriptEntry]

Map of Control blocks to Script version pair.

unknown: dict[Key, bytes]

Unknown key-value pairs for this input.

witness_script: Script | None

The witness script for this input.

witness_utxo: TxOut | None

The transaction output this input spends from. Should only be Option::Some for inputs which spend segwit outputs, including P2SH embedded ones.

class bdkpython.bdk.InternalError[source]

Bases: Exception

class bdkpython.bdk.IpAddress(*args, **kwargs)[source]

Bases: object

An IP address to connect to over TCP.

classmethod from_ipv4(q1: int, q2: int, q3: int, q4: int)[source]

Build an IPv4 address.

classmethod from_ipv6(a: int, b: int, c: int, d: int, e: int, f: int, g: int, h: int)[source]

Build an IPv6 address.

class bdkpython.bdk.IpAddressProtocol(*args, **kwargs)[source]

Bases: Protocol

An IP address to connect to over TCP.

class bdkpython.bdk.Key(*, type_value: int, key: bytes)[source]

Bases: object

key: bytes

The key itself in raw byte form. <key> := <keylen> <keytype> <keydata>

type_value: int

The type of this PSBT key.

class bdkpython.bdk.KeySource(*, fingerprint: str, path: DerivationPath)[source]

Bases: object

fingerprint: str

A fingerprint

path: DerivationPath

A BIP-32 derivation path.

class bdkpython.bdk.KeychainAndIndex(*, keychain: KeychainKind, index: int)[source]

Bases: object

The keychain kind and the index in that keychain.

index: int

The index in the keychain.

keychain: KeychainKind

Type of keychains.

class bdkpython.bdk.KeychainKind(*values)[source]

Bases: Enum

Types of keychains.

EXTERNAL = 0

External keychain, used for deriving recipient addresses.

INTERNAL = 1

Internal keychain, used for deriving change addresses.

class bdkpython.bdk.LoadWithPersistError[source]

Bases: Exception

exception CouldNotLoad[source]

Bases: LoadWithPersistError

exception InvalidChangeSet(error_message)[source]

Bases: LoadWithPersistError

exception Persist(error_message)[source]

Bases: LoadWithPersistError

class bdkpython.bdk.LocalChainChangeSet(*, changes: List[ChainChange])[source]

Bases: object

Changes to the local chain

changes: List[ChainChange]
class bdkpython.bdk.LocalOutput(*, outpoint: OutPoint, txout: TxOut, keychain: KeychainKind, is_spent: bool, derivation_index: int, chain_position: ChainPosition)[source]

Bases: object

An unspent output owned by a [Wallet].

chain_position: ChainPosition

The position of the output in the blockchain.

derivation_index: int

The derivation index for the script pubkey in the wallet

is_spent: bool

Whether this UTXO is spent or not

keychain: KeychainKind

Type of keychain

outpoint: OutPoint

Reference to a transaction output

txout: TxOut

Transaction output

class bdkpython.bdk.LockTime[source]

Bases: object

BLOCKS[source]

alias of BLOCKS

SECONDS[source]

alias of SECONDS

is_BLOCKS() bool[source]
is_SECONDS() bool[source]
is_blocks() bool[source]
is_seconds() bool[source]
class bdkpython.bdk.MiniscriptError[source]

Bases: Exception

exception AbsoluteLockTime[source]

Bases: MiniscriptError

exception AddrError(error_message)[source]

Bases: MiniscriptError

exception AddrP2shError(error_message)[source]

Bases: MiniscriptError

exception AnalysisError(error_message)[source]

Bases: MiniscriptError

exception AtOutsideOr[source]

Bases: MiniscriptError

exception BadDescriptor(error_message)[source]

Bases: MiniscriptError

exception BareDescriptorAddr[source]

Bases: MiniscriptError

exception CmsTooManyKeys(keys)[source]

Bases: MiniscriptError

exception ContextError(error_message)[source]

Bases: MiniscriptError

exception CouldNotSatisfy[source]

Bases: MiniscriptError

exception ExpectedChar(char)[source]

Bases: MiniscriptError

exception ImpossibleSatisfaction[source]

Bases: MiniscriptError

exception InvalidOpcode[source]

Bases: MiniscriptError

exception InvalidPush[source]

Bases: MiniscriptError

exception LiftError(error_message)[source]

Bases: MiniscriptError

exception MaxRecursiveDepthExceeded[source]

Bases: MiniscriptError

exception MissingSig[source]

Bases: MiniscriptError

exception MultiATooManyKeys(keys)[source]

Bases: MiniscriptError

exception MultiColon[source]

Bases: MiniscriptError

exception MultipathDescLenMismatch[source]

Bases: MiniscriptError

exception NonMinimalVerify(error_message)[source]

Bases: MiniscriptError

exception NonStandardBareScript[source]

Bases: MiniscriptError

exception NonTopLevel(error_message)[source]

Bases: MiniscriptError

exception ParseThreshold[source]

Bases: MiniscriptError

exception PolicyError(error_message)[source]

Bases: MiniscriptError

exception PubKeyCtxError[source]

Bases: MiniscriptError

exception RelativeLockTime[source]

Bases: MiniscriptError

exception Script(error_message)[source]

Bases: MiniscriptError

exception Secp(error_message)[source]

Bases: MiniscriptError

exception Threshold[source]

Bases: MiniscriptError

exception TrNoScriptCode[source]

Bases: MiniscriptError

exception Trailing(error_message)[source]

Bases: MiniscriptError

exception TypeCheck(error_message)[source]

Bases: MiniscriptError

exception Unexpected(error_message)[source]

Bases: MiniscriptError

exception UnexpectedStart[source]

Bases: MiniscriptError

exception UnknownWrapper(char)[source]

Bases: MiniscriptError

exception Unprintable(byte)[source]

Bases: MiniscriptError

class bdkpython.bdk.Mnemonic(word_count: WordCount)[source]

Bases: object

A mnemonic seed phrase to recover a BIP-32 wallet.

classmethod from_entropy(entropy: bytes)[source]

Construct a mnemonic given an array of bytes. Note that using weak entropy will result in a loss of funds. To ensure the entropy is generated properly, read about your operating system specific ways to generate secure random numbers.

classmethod from_string(mnemonic: str)[source]

Parse a string as a mnemonic seed phrase.

class bdkpython.bdk.MnemonicProtocol(*args, **kwargs)[source]

Bases: Protocol

A mnemonic seed phrase to recover a BIP-32 wallet.

class bdkpython.bdk.Network(*values)[source]

Bases: Enum

The cryptocurrency network to act on.

This is an exhaustive enum, meaning that we cannot add any future networks without defining a new, incompatible version of this type. If you are using this type directly and wish to support the new network, this will be a breaking change to your APIs and likely require changes in your code.

If you are concerned about forward compatibility, consider using T: Into<Params> instead of this type as a parameter to functions in your public API, or directly using the Params type.

BITCOIN = 0
REGTEST = 4
SIGNET = 3
TESTNET = 1
TESTNET4 = 2
class bdkpython.bdk.OutPoint(*, txid: Txid, vout: int)[source]

Bases: object

A reference to an unspent output by TXID and output index.

txid: Txid

The transaction.

vout: int

The index of the output in the transaction.

class bdkpython.bdk.ParseAmountError[source]

Bases: Exception

exception InputTooLarge[source]

Bases: ParseAmountError

exception InvalidCharacter(error_message)[source]

Bases: ParseAmountError

exception MissingDigits[source]

Bases: ParseAmountError

exception OtherParseAmountErr[source]

Bases: ParseAmountError

exception OutOfRange[source]

Bases: ParseAmountError

exception TooPrecise[source]

Bases: ParseAmountError

class bdkpython.bdk.Peer(*, address: IpAddress, port: int | None, v2_transport: bool)[source]

Bases: object

A peer to connect to over the Bitcoin peer-to-peer network.

address: IpAddress

The IP address to reach the node.

port: int | None

The port to reach the node. If none is provided, the default port for the selected network will be used.

v2_transport: bool

Does the remote node offer encrypted peer-to-peer connection.

class bdkpython.bdk.Persistence[source]

Bases: object

Definition of a wallet persistence implementation.

initialize()[source]

Initialize the total aggregate ChangeSet for the underlying wallet.

persist(changeset: ChangeSet)[source]

Persist a ChangeSet to the total aggregate changeset of the wallet.

class bdkpython.bdk.PersistenceError[source]

Bases: Exception

exception Reason(error_message)[source]

Bases: PersistenceError

class bdkpython.bdk.PersistenceImpl(*args, **kwargs)[source]

Bases: object

Definition of a wallet persistence implementation.

initialize() ChangeSet[source]

Initialize the total aggregate ChangeSet for the underlying wallet.

persist(changeset: ChangeSet) None[source]

Persist a ChangeSet to the total aggregate changeset of the wallet.

class bdkpython.bdk.PersistenceProtocol(*args, **kwargs)[source]

Bases: Protocol

Definition of a wallet persistence implementation.

initialize()[source]

Initialize the total aggregate ChangeSet for the underlying wallet.

persist(changeset: ChangeSet)[source]

Persist a ChangeSet to the total aggregate changeset of the wallet.

class bdkpython.bdk.Persister(*args, **kwargs)[source]

Bases: object

Wallet backend implementations.

classmethod custom(persistence: Persistence)[source]

Use a native persistence layer.

classmethod new_in_memory()[source]

Create a new connection in memory.

classmethod new_sqlite(path: str)[source]

Create a new Sqlite connection at the specified file path.

class bdkpython.bdk.PersisterProtocol(*args, **kwargs)[source]

Bases: Protocol

Wallet backend implementations.

class bdkpython.bdk.PkOrF[source]

Bases: object

FINGERPRINT[source]

alias of FINGERPRINT

PUBKEY[source]

alias of PUBKEY

X_ONLY_PUBKEY[source]

alias of X_ONLY_PUBKEY

is_FINGERPRINT() bool[source]
is_PUBKEY() bool[source]
is_X_ONLY_PUBKEY() bool[source]
is_fingerprint() bool[source]
is_pubkey() bool[source]
is_x_only_pubkey() bool[source]
class bdkpython.bdk.Policy(*args, **kwargs)[source]

Bases: object

Descriptor spending policy

as_string() str[source]
contribution() Satisfaction[source]
id() str[source]
item() SatisfiableItem[source]
requires_path() bool[source]
satisfaction() Satisfaction[source]
class bdkpython.bdk.PolicyProtocol(*args, **kwargs)[source]

Bases: Protocol

Descriptor spending policy

as_string()[source]
contribution()[source]
id()[source]
item()[source]
requires_path()[source]
satisfaction()[source]
class bdkpython.bdk.ProprietaryKey(*, prefix: bytes, subtype: int, key: bytes)[source]

Bases: object

key: bytes

Additional key bytes (like serialized public key data etc)

prefix: bytes

Proprietary type prefix used for grouping together keys under some application and avoid namespace collision

subtype: int

Custom proprietary subtype

class bdkpython.bdk.Psbt(psbt_base64: str)[source]

Bases: object

A Partially Signed Transaction.

combine(other: Psbt) Psbt[source]

Combines this Psbt with other PSBT as described by BIP 174.

In accordance with BIP 174 this function is commutative i.e., A.combine(B) == B.combine(A)

extract_tx() Transaction[source]

Extracts the Transaction from a Psbt by filling in the available signature information.

#### Errors

ExtractTxError variants will contain either the Psbt itself or the Transaction that was extracted. These can be extracted from the Errors in order to recover. See the error documentation for info on the variants. In general, it covers large fees.

fee() int[source]

Calculates transaction fee.

‘Fee’ being the amount that will be paid for mining a transaction with the current inputs and outputs i.e., the difference in value of the total inputs and the total outputs.

#### Errors

  • MissingUtxo when UTXO information for any input is not present or is invalid.

  • NegativeFee if calculated value is negative.

  • FeeOverflow if an integer overflow occurs.

finalize() FinalizedPsbtResult[source]

Finalizes the current PSBT and produces a result indicating

whether the finalization was successful or not.

classmethod from_file(path: str)[source]

Create a new Psbt from a .psbt file.

classmethod from_unsigned_tx(tx: Transaction)[source]

Creates a PSBT from an unsigned transaction.

# Errors

If transactions is not unsigned.

input() List[Input][source]

The corresponding key-value map for each input in the unsigned transaction.

json_serialize() str[source]

Serializes the PSBT into a JSON string representation.

serialize() str[source]

Serialize the PSBT into a base64-encoded string.

spend_utxo(input_index: int) str[source]

Returns the spending utxo for this PSBT’s input at input_index.

write_to_file(path: str) None[source]

Write the Psbt to a file. Note that the file must not yet exist.

class bdkpython.bdk.PsbtError[source]

Bases: Exception

exception CombineInconsistentKeySources(xpub)[source]

Bases: PsbtError

exception ConsensusEncoding(encoding_error)[source]

Bases: PsbtError

exception DuplicateKey(key)[source]

Bases: PsbtError

exception FeeOverflow[source]

Bases: PsbtError

exception InvalidControlBlock[source]

Bases: PsbtError

exception InvalidEcdsaSignature(error_message)[source]

Bases: PsbtError

exception InvalidHash(hash)[source]

Bases: PsbtError

exception InvalidKey(key)[source]

Bases: PsbtError

exception InvalidLeafVersion[source]

Bases: PsbtError

exception InvalidMagic[source]

Bases: PsbtError

exception InvalidPreimageHashPair[source]

Bases: PsbtError

exception InvalidProprietaryKey[source]

Bases: PsbtError

exception InvalidPublicKey(error_message)[source]

Bases: PsbtError

exception InvalidSecp256k1PublicKey(secp256k1_error)[source]

Bases: PsbtError

exception InvalidSeparator[source]

Bases: PsbtError

exception InvalidTaprootSignature(error_message)[source]

Bases: PsbtError

exception InvalidXOnlyPublicKey[source]

Bases: PsbtError

exception Io(error_message)[source]

Bases: PsbtError

exception MissingUtxo[source]

Bases: PsbtError

exception MustHaveUnsignedTx[source]

Bases: PsbtError

exception NegativeFee[source]

Bases: PsbtError

exception NoMorePairs[source]

Bases: PsbtError

exception NonStandardSighashType(sighash)[source]

Bases: PsbtError

exception OtherPsbtErr[source]

Bases: PsbtError

exception PartialDataConsumption[source]

Bases: PsbtError

exception PsbtUtxoOutOfBounds[source]

Bases: PsbtError

exception TapTree(error_message)[source]

Bases: PsbtError

exception Taproot[source]

Bases: PsbtError

exception UnexpectedUnsignedTx[source]

Bases: PsbtError

exception UnsignedTxHasScriptSigs[source]

Bases: PsbtError

exception UnsignedTxHasScriptWitnesses[source]

Bases: PsbtError

exception Version(error_message)[source]

Bases: PsbtError

exception XPubKey[source]

Bases: PsbtError

class bdkpython.bdk.PsbtFinalizeError[source]

Bases: Exception

exception InputError(reason, index)[source]

Bases: PsbtFinalizeError

exception InputIdxOutofBounds(psbt_inp, requested)[source]

Bases: PsbtFinalizeError

exception WrongInputCount(in_tx, in_map)[source]

Bases: PsbtFinalizeError

class bdkpython.bdk.PsbtParseError[source]

Bases: Exception

exception Base64Encoding(error_message)[source]

Bases: PsbtParseError

exception PsbtEncoding(error_message)[source]

Bases: PsbtParseError

class bdkpython.bdk.PsbtProtocol(*args, **kwargs)[source]

Bases: Protocol

A Partially Signed Transaction.

combine(other: Psbt)[source]

Combines this Psbt with other PSBT as described by BIP 174.

In accordance with BIP 174 this function is commutative i.e., A.combine(B) == B.combine(A)

extract_tx()[source]

Extracts the Transaction from a Psbt by filling in the available signature information.

#### Errors

ExtractTxError variants will contain either the Psbt itself or the Transaction that was extracted. These can be extracted from the Errors in order to recover. See the error documentation for info on the variants. In general, it covers large fees.

fee()[source]

Calculates transaction fee.

‘Fee’ being the amount that will be paid for mining a transaction with the current inputs and outputs i.e., the difference in value of the total inputs and the total outputs.

#### Errors

  • MissingUtxo when UTXO information for any input is not present or is invalid.

  • NegativeFee if calculated value is negative.

  • FeeOverflow if an integer overflow occurs.

finalize()[source]

Finalizes the current PSBT and produces a result indicating

whether the finalization was successful or not.

input()[source]

The corresponding key-value map for each input in the unsigned transaction.

json_serialize()[source]

Serializes the PSBT into a JSON string representation.

serialize()[source]

Serialize the PSBT into a base64-encoded string.

spend_utxo(input_index: int)[source]

Returns the spending utxo for this PSBT’s input at input_index.

write_to_file(path: str)[source]

Write the Psbt to a file. Note that the file must not yet exist.

class bdkpython.bdk.RecoveryPoint(*values)[source]

Bases: Enum

GENESIS_BLOCK = 0
SEGWIT_ACTIVATION = 1
TAPROOT_ACTIVATION = 2
class bdkpython.bdk.RequestBuilderError[source]

Bases: Exception

exception RequestAlreadyConsumed[source]

Bases: RequestBuilderError

class bdkpython.bdk.Satisfaction[source]

Bases: object

COMPLETE[source]

alias of COMPLETE

NONE[source]

alias of NONE

PARTIAL[source]

alias of PARTIAL

PARTIAL_COMPLETE[source]

alias of PARTIAL_COMPLETE

is_COMPLETE() bool[source]
is_NONE() bool[source]
is_PARTIAL() bool[source]
is_PARTIAL_COMPLETE() bool[source]
is_complete() bool[source]
is_none() bool[source]
is_partial() bool[source]
is_partial_complete() bool[source]
class bdkpython.bdk.SatisfiableItem[source]

Bases: object

ABSOLUTE_TIMELOCK[source]

alias of ABSOLUTE_TIMELOCK

ECDSA_SIGNATURE[source]

alias of ECDSA_SIGNATURE

HASH160_PREIMAGE[source]

alias of HASH160_PREIMAGE

HASH256_PREIMAGE[source]

alias of HASH256_PREIMAGE

MULTISIG[source]

alias of MULTISIG

RELATIVE_TIMELOCK[source]

alias of RELATIVE_TIMELOCK

RIPEMD160_PREIMAGE[source]

alias of RIPEMD160_PREIMAGE

SCHNORR_SIGNATURE[source]

alias of SCHNORR_SIGNATURE

SHA256_PREIMAGE[source]

alias of SHA256_PREIMAGE

THRESH[source]

alias of THRESH

is_ABSOLUTE_TIMELOCK() bool[source]
is_ECDSA_SIGNATURE() bool[source]
is_HASH160_PREIMAGE() bool[source]
is_HASH256_PREIMAGE() bool[source]
is_MULTISIG() bool[source]
is_RELATIVE_TIMELOCK() bool[source]
is_RIPEMD160_PREIMAGE() bool[source]
is_SCHNORR_SIGNATURE() bool[source]
is_SHA256_PREIMAGE() bool[source]
is_THRESH() bool[source]
is_absolute_timelock() bool[source]
is_ecdsa_signature() bool[source]
is_hash160_preimage() bool[source]
is_hash256_preimage() bool[source]
is_multisig() bool[source]
is_relative_timelock() bool[source]
is_ripemd160_preimage() bool[source]
is_schnorr_signature() bool[source]
is_sha256_preimage() bool[source]
is_thresh() bool[source]
class bdkpython.bdk.ScanType[source]

Bases: object

Sync a wallet from the last known block hash or recover a wallet from a specified recovery point.

RECOVERY[source]

alias of RECOVERY

SYNC[source]

alias of SYNC

is_RECOVERY() bool[source]
is_SYNC() bool[source]
is_recovery() bool[source]
is_sync() bool[source]
class bdkpython.bdk.Script(raw_output_script: bytes)[source]

Bases: object

A bitcoin script: https://en.bitcoin.it/wiki/Script

to_bytes() bytes[source]

Convert a script into an array of bytes.

class bdkpython.bdk.ScriptAmount(*, script: Script, amount: Amount)[source]

Bases: object

A bitcoin script and associated amount.

amount: Amount

The amount owned by the script.

script: Script

The underlying script.

class bdkpython.bdk.ScriptProtocol(*args, **kwargs)[source]

Bases: Protocol

A bitcoin script: https://en.bitcoin.it/wiki/Script

to_bytes()[source]

Convert a script into an array of bytes.

class bdkpython.bdk.SentAndReceivedValues(*, sent: Amount, received: Amount)[source]

Bases: object

The total value sent and received.

received: Amount

The amount received in the transaction, possibly as a change output(s).

sent: Amount

Amount sent in the transaction.

class bdkpython.bdk.ServerFeaturesRes(*, server_version: str, genesis_hash: BlockHash, protocol_min: str, protocol_max: str, hash_function: str | None, pruning: int | None)[source]

Bases: object

Response to an ElectrumClient.server_features request.

genesis_hash: BlockHash

Hash of the genesis block.

hash_function: str | None

Hash function used to create the ScriptHash.

protocol_max: str

Maximum supported version of the protocol.

protocol_min: str

Minimum supported version of the protocol.

pruning: int | None

Pruned height of the server.

server_version: str

Server version reported.

class bdkpython.bdk.SignOptions(*, trust_witness_utxo: bool, assume_height: int | None, allow_all_sighashes: bool, try_finalize: bool, sign_with_tap_internal_key: bool, allow_grinding: bool)[source]

Bases: object

Options for a software signer.

Adjust the behavior of our software signers and the way a transaction is finalized.

allow_all_sighashes: bool

Whether the signer should use the sighash_type set in the PSBT when signing, no matter what its value is

Defaults to false which will only allow signing using SIGHASH_ALL.

allow_grinding: bool

Whether we should grind ECDSA signature to ensure signing with low r or not. Defaults to true, i.e., we always grind ECDSA signature to sign with low r.

assume_height: int | None

Whether the wallet should assume a specific height has been reached when trying to finalize a transaction

The wallet will only “use” a timelock to satisfy the spending policy of an input if the timelock height has already been reached. This option allows overriding the “current height” to let the wallet use timelocks in the future to spend a coin.

sign_with_tap_internal_key: bool

Whether we should try to sign a taproot transaction with the taproot internal key or not. This option is ignored if we’re signing a non-taproot PSBT.

Defaults to true, i.e., we always try to sign with the taproot internal key.

trust_witness_utxo: bool

Whether the signer should trust the witness_utxo, if the non_witness_utxo hasn’t been provided

Defaults to false to mitigate the “SegWit bug” which could trick the wallet into paying a fee larger than expected.

Some wallets, especially if relatively old, might not provide the non_witness_utxo for SegWit transactions in the PSBT they generate: in those cases setting this to true should correctly produce a signature, at the expense of an increased trust in the creator of the PSBT.

For more details see: <https://blog.trezor.io/details-of-firmware-updates-for-trezor-one-version-1-9-1-and-trezor-model-t-version-2-3-1-1eba8f60f2dd>

try_finalize: bool

Whether to try finalizing the PSBT after the inputs are signed.

Defaults to true which will try finalizing PSBT after inputs are signed.

class bdkpython.bdk.SignerError[source]

Bases: Exception

exception External(error_message)[source]

Bases: SignerError

exception InputIndexOutOfRange[source]

Bases: SignerError

exception InvalidKey[source]

Bases: SignerError

exception InvalidNonWitnessUtxo[source]

Bases: SignerError

exception InvalidSighash[source]

Bases: SignerError

exception MiniscriptPsbt(error_message)[source]

Bases: SignerError

exception MissingHdKeypath[source]

Bases: SignerError

exception MissingKey[source]

Bases: SignerError

exception MissingNonWitnessUtxo[source]

Bases: SignerError

exception MissingWitnessScript[source]

Bases: SignerError

exception MissingWitnessUtxo[source]

Bases: SignerError

exception NonStandardSighash[source]

Bases: SignerError

exception Psbt(error_message)[source]

Bases: SignerError

exception SighashP2wpkh(error_message)[source]

Bases: SignerError

exception SighashTaproot(error_message)[source]

Bases: SignerError

exception TxInputsIndexError(error_message)[source]

Bases: SignerError

exception UserCanceled[source]

Bases: SignerError

class bdkpython.bdk.Socks5Proxy(*, address: IpAddress, port: int)[source]

Bases: object

A proxy to route network traffic, most likely through a Tor daemon. Normally this proxy is exposed at 127.0.0.1:9050.

address: IpAddress

The IP address, likely 127.0.0.1

port: int

The listening port, likely 9050

class bdkpython.bdk.SyncRequest(*args, **kwargs)[source]

Bases: object

class bdkpython.bdk.SyncRequestBuilder(*args, **kwargs)[source]

Bases: object

build() SyncRequest[source]
inspect_spks(inspector: SyncScriptInspector) SyncRequestBuilder[source]
class bdkpython.bdk.SyncRequestBuilderProtocol(*args, **kwargs)[source]

Bases: Protocol

build()[source]
inspect_spks(inspector: SyncScriptInspector)[source]
class bdkpython.bdk.SyncRequestProtocol(*args, **kwargs)[source]

Bases: Protocol

class bdkpython.bdk.SyncScriptInspector[source]

Bases: object

inspect(script: Script, total: int)[source]
class bdkpython.bdk.SyncScriptInspectorImpl(*args, **kwargs)[source]

Bases: object

inspect(script: Script, total: int) None[source]
class bdkpython.bdk.SyncScriptInspectorProtocol(*args, **kwargs)[source]

Bases: Protocol

inspect(script: Script, total: int)[source]
class bdkpython.bdk.TapKeyOrigin(*, tap_leaf_hashes: List[str], key_source: KeySource)[source]

Bases: object

key_source: KeySource

key source

tap_leaf_hashes: List[str]

leaf hashes as hex strings

class bdkpython.bdk.TapScriptEntry(*, script: Script, leaf_version: int)[source]

Bases: object

leaf_version: int

leaf version

script(reuse existing `Script` FFI type): Script

script (reuse existing Script FFI type)

class bdkpython.bdk.TapScriptSigKey(*, xonly_pubkey: str, tap_leaf_hash: str)[source]

Bases: object

tap_leaf_hash: str

Taproot-tagged hash with tag “TapLeaf”. This is used for computing tapscript script spend hash.

xonly_pubkey: str

An x-only public key, used for verification of Taproot signatures and serialized according to BIP-340.

class bdkpython.bdk.Transaction(transaction_bytes: bytes)[source]

Bases: object

Bitcoin transaction. An authenticated movement of coins.

compute_txid() Txid[source]

Computes the Txid. Hashes the transaction excluding the segwit data (i.e. the marker, flag bytes, and the witness fields themselves).

compute_wtxid() Wtxid[source]

Compute the Wtxid, which includes the witness in the transaction hash.

input() List[TxIn][source]

List of transaction inputs.

is_coinbase() bool[source]

Checks if this is a coinbase transaction. The first transaction in the block distributes the mining reward and is called the coinbase transaction. It is impossible to check if the transaction is first in the block, so this function checks the structure of the transaction instead - the previous output must be all-zeros (creates satoshis “out of thin air”).

is_explicitly_rbf() bool[source]

Returns true if the transaction itself opted in to be BIP-125-replaceable (RBF).

# Warning

Incorrectly relying on RBF may lead to monetary loss!

This does not cover the case where a transaction becomes replaceable due to ancestors being RBF. Please note that transactions may be replaced even if they do not include the RBF signal: <https://bitcoinops.org/en/newsletters/2022/10/19/#transaction-replacement-option>.

is_lock_time_enabled() bool[source]

Returns true if this transactions nLockTime is enabled ([BIP-65]).

[BIP-65]: https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki

lock_time() int[source]

Block height or timestamp. Transaction cannot be included in a block until this height/time.

/// ### Relevant BIPs

output() List[TxOut][source]

List of transaction outputs.

serialize() bytes[source]

Serialize transaction into consensus-valid format. See https://docs.rs/bitcoin/latest/bitcoin/struct.Transaction.html#serialization-notes for more notes on transaction serialization.

total_size() int[source]

Returns the total transaction size

Total transaction size is the transaction size in bytes serialized as described in BIP144, including base data and witness data.

version() int[source]

The protocol version, is currently expected to be 1 or 2 (BIP 68).

vsize() int[source]

Returns the “virtual size” (vsize) of this transaction.

Will be ceil(weight / 4.0). Note this implements the virtual size as per [BIP141], which is different to what is implemented in Bitcoin Core. > Virtual transaction size is defined as Transaction weight / 4 (rounded up to the next integer).

[BIP141]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki

weight() int[source]

Returns the weight of this transaction, as defined by BIP-141.

> Transaction weight is defined as Base transaction size * 3 + Total transaction size (ie. > the same method as calculating Block weight from Base size and Total size).

For transactions with an empty witness, this is simply the consensus-serialized size times four. For transactions with a witness, this is the non-witness consensus-serialized size multiplied by three plus the with-witness consensus-serialized size.

For transactions with no inputs, this function will return a value 2 less than the actual weight of the serialized transaction. The reason is that zero-input transactions, post-segwit, cannot be unambiguously serialized; we make a choice that adds two extra bytes. For more details see [BIP 141](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki) which uses a “input count” of 0x00 as a marker for a Segwit-encoded transaction.

If you need to use 0-input transactions, we strongly recommend you do so using the PSBT API. The unsigned transaction encoded within PSBT is always a non-segwit transaction and can therefore avoid this ambiguity.

class bdkpython.bdk.TransactionError[source]

Bases: Exception

exception InvalidChecksum(expected, actual)[source]

Bases: TransactionError

exception Io[source]

Bases: TransactionError

exception NonMinimalVarInt[source]

Bases: TransactionError

exception OtherTransactionErr[source]

Bases: TransactionError

exception OversizedVectorAllocation[source]

Bases: TransactionError

exception ParseFailed[source]

Bases: TransactionError

exception UnsupportedSegwitFlag(flag)[source]

Bases: TransactionError

class bdkpython.bdk.TransactionProtocol(*args, **kwargs)[source]

Bases: Protocol

Bitcoin transaction. An authenticated movement of coins.

compute_txid()[source]

Computes the Txid. Hashes the transaction excluding the segwit data (i.e. the marker, flag bytes, and the witness fields themselves).

compute_wtxid()[source]

Compute the Wtxid, which includes the witness in the transaction hash.

input()[source]

List of transaction inputs.

is_coinbase()[source]

Checks if this is a coinbase transaction. The first transaction in the block distributes the mining reward and is called the coinbase transaction. It is impossible to check if the transaction is first in the block, so this function checks the structure of the transaction instead - the previous output must be all-zeros (creates satoshis “out of thin air”).

is_explicitly_rbf()[source]

Returns true if the transaction itself opted in to be BIP-125-replaceable (RBF).

# Warning

Incorrectly relying on RBF may lead to monetary loss!

This does not cover the case where a transaction becomes replaceable due to ancestors being RBF. Please note that transactions may be replaced even if they do not include the RBF signal: <https://bitcoinops.org/en/newsletters/2022/10/19/#transaction-replacement-option>.

is_lock_time_enabled()[source]

Returns true if this transactions nLockTime is enabled ([BIP-65]).

[BIP-65]: https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki

lock_time()[source]

Block height or timestamp. Transaction cannot be included in a block until this height/time.

/// ### Relevant BIPs

output()[source]

List of transaction outputs.

serialize()[source]

Serialize transaction into consensus-valid format. See https://docs.rs/bitcoin/latest/bitcoin/struct.Transaction.html#serialization-notes for more notes on transaction serialization.

total_size()[source]

Returns the total transaction size

Total transaction size is the transaction size in bytes serialized as described in BIP144, including base data and witness data.

version()[source]

The protocol version, is currently expected to be 1 or 2 (BIP 68).

vsize()[source]

Returns the “virtual size” (vsize) of this transaction.

Will be ceil(weight / 4.0). Note this implements the virtual size as per [BIP141], which is different to what is implemented in Bitcoin Core. > Virtual transaction size is defined as Transaction weight / 4 (rounded up to the next integer).

[BIP141]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki

weight()[source]

Returns the weight of this transaction, as defined by BIP-141.

> Transaction weight is defined as Base transaction size * 3 + Total transaction size (ie. > the same method as calculating Block weight from Base size and Total size).

For transactions with an empty witness, this is simply the consensus-serialized size times four. For transactions with a witness, this is the non-witness consensus-serialized size multiplied by three plus the with-witness consensus-serialized size.

For transactions with no inputs, this function will return a value 2 less than the actual weight of the serialized transaction. The reason is that zero-input transactions, post-segwit, cannot be unambiguously serialized; we make a choice that adds two extra bytes. For more details see [BIP 141](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki) which uses a “input count” of 0x00 as a marker for a Segwit-encoded transaction.

If you need to use 0-input transactions, we strongly recommend you do so using the PSBT API. The unsigned transaction encoded within PSBT is always a non-segwit transaction and can therefore avoid this ambiguity.

class bdkpython.bdk.Tx(*, txid: Txid, version: int, locktime: int, size: int, weight: int, fee: int, status: TxStatus)[source]

Bases: object

Bitcoin transaction metadata.

fee: int

The fee of this transaction in satoshis.

locktime: int

The block height or time restriction on the transaction.

size: int

The size of the transaction in bytes.

status: TxStatus

Confirmation status and data.

txid: Txid

The transaction identifier.

version: int

The transaction version, of which 0, 1, 2 are standard.

weight: int

The weight units of this transaction.

class bdkpython.bdk.TxBuilder[source]

Bases: object

A TxBuilder is created by calling build_tx on a wallet. After assigning it, you set options on it until finally calling finish to consume the builder and generate the transaction.

add_data(data: bytes) TxBuilder[source]

Add data as an output using OP_RETURN.

add_global_xpubs() TxBuilder[source]

Fill-in the PSBT_GLOBAL_XPUB field with the extended keys contained in both the external and internal descriptors.

This is useful for offline signers that take part to a multisig. Some hardware wallets like BitBox and ColdCard are known to require this.

add_recipient(script: Script, amount: Amount) TxBuilder[source]

Add a recipient to the internal list of recipients.

add_unspendable(unspendable: OutPoint) TxBuilder[source]

Add a utxo to the internal list of unspendable utxos.

It’s important to note that the “must-be-spent” utxos added with TxBuilder::add_utxo have priority over this.

add_utxo(outpoint: OutPoint) TxBuilder[source]

Add a utxo to the internal list of utxos that must be spent.

These have priority over the “unspendable” utxos, meaning that if a utxo is present both in the “utxos” and the “unspendable” list, it will be spent.

add_utxos(outpoints: List[OutPoint]) TxBuilder[source]

Add the list of outpoints to the internal list of UTXOs that must be spent.

allow_dust(allow_dust: bool) TxBuilder[source]

Set whether or not the dust limit is checked.

Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.

change_policy(change_policy: ChangeSpendPolicy) TxBuilder[source]

Set a specific ChangeSpendPolicy. See TxBuilder::do_not_spend_change and TxBuilder::only_spend_change for some shortcuts. This method assumes the presence of an internal keychain, otherwise it has no effect.

current_height(height: int) TxBuilder[source]

Set the current blockchain height.

This will be used to:

1. Set the nLockTime for preventing fee sniping. Note: This will be ignored if you manually specify a nlocktime using TxBuilder::nlocktime.

2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at current_height, we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs, manually add them using TxBuilder::add_utxos. In both cases, if you don’t provide a current height, we use the last sync height.

do_not_spend_change() TxBuilder[source]

Do not spend change outputs.

This effectively adds all the change outputs to the “unspendable” list. See TxBuilder::unspendable. This method assumes the presence of an internal keychain, otherwise it has no effect.

drain_to(script: Script) TxBuilder[source]

Sets the address to drain excess coins to.

Usually, when there are excess coins they are sent to a change address generated by the wallet. This option replaces the usual change address with an arbitrary script_pubkey of your choosing. Just as with a change output, if the drain output is not needed (the excess coins are too small) it will not be included in the resulting transaction. The only difference is that it is valid to use drain_to without setting any ordinary recipients with add_recipient (but it is perfectly fine to add recipients as well).

If you choose not to set any recipients, you should provide the utxos that the transaction should spend via add_utxos. drain_to is very useful for draining all the coins in a wallet with drain_wallet to a single address.

drain_wallet() TxBuilder[source]

Spend all the available inputs. This respects filters like TxBuilder::unspendable and the change policy.

exclude_below_confirmations(min_confirms: int) TxBuilder[source]

Excludes any outpoints whose enclosing transaction has fewer than min_confirms confirmations.

min_confirms is the minimum number of confirmations a transaction must have in order for its outpoints to remain spendable. - Passing 0 will include all transactions (no filtering). - Passing 1 will exclude all unconfirmed transactions (equivalent to exclude_unconfirmed). - Passing 6 will only allow outpoints from transactions with at least 6 confirmations.

If you chain this with other filtering methods, the final set of unspendable outpoints will be the union of all filters.

exclude_unconfirmed() TxBuilder[source]

Exclude outpoints whose enclosing transaction is unconfirmed. This is a shorthand for exclude_below_confirmations(1).

fee_absolute(fee_amount: Amount) TxBuilder[source]

Set an absolute fee The fee_absolute method refers to the absolute transaction fee in Amount. If anyone sets both the fee_absolute method and the fee_rate method, the FeePolicy enum will be set by whichever method was called last, as the FeeRate and FeeAmount are mutually exclusive.

Note that this is really a minimum absolute fee – it’s possible to overshoot it slightly since adding a change output to drain the remaining excess might not be viable.

fee_rate(fee_rate: FeeRate) TxBuilder[source]

Set a custom fee rate.

This method sets the mining fee paid by the transaction as a rate on its size. This means that the total fee paid is equal to fee_rate times the size of the transaction. Default is 1 sat/vB in accordance with Bitcoin Core’s default relay policy.

Note that this is really a minimum feerate – it’s possible to overshoot it slightly since adding a change output to drain the remaining excess might not be viable.

finish(wallet: Wallet) Psbt[source]

Finish building the transaction.

Uses the thread-local random number generator (rng).

Returns a new Psbt per BIP174.

WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See Wallet::reveal_next_address.

manually_selected_only() TxBuilder[source]

Only spend utxos added by TxBuilder::add_utxo.

The wallet will not add additional utxos to the transaction even if they are needed to make the transaction valid.

nlocktime(locktime: LockTime) TxBuilder[source]

Use a specific nLockTime while creating the transaction.

This can cause conflicts if the wallet’s descriptors contain an “after” (OP_CLTV) operator.

only_spend_change() TxBuilder[source]

Only spend change outputs.

This effectively adds all the non-change outputs to the “unspendable” list. See TxBuilder::unspendable. This method assumes the presence of an internal keychain, otherwise it has no effect.

policy_path(policy_path: dict[str, List[int]], keychain: KeychainKind) TxBuilder[source]

The TxBuilder::policy_path is a complex API. See the Rust docs for complete information: https://docs.rs/bdk_wallet/latest/bdk_wallet/struct.TxBuilder.html#method.policy_path

set_exact_sequence(nsequence: int) TxBuilder[source]

Set an exact nSequence value.

This can cause conflicts if the wallet’s descriptors contain an “older” (OP_CSV) operator and the given nsequence is lower than the CSV value.

set_recipients(recipients: List[ScriptAmount]) TxBuilder[source]

Replace the recipients already added with a new list of recipients.

unspendable(unspendable: List[OutPoint]) TxBuilder[source]

Replace the internal list of unspendable utxos with a new list.

It’s important to note that the “must-be-spent” utxos added with TxBuilder::add_utxo have priority over these.

version(version: int) TxBuilder[source]

Build a transaction with a specific version.

The version should always be greater than 0 and greater than 1 if the wallet’s descriptors contain an “older” (OP_CSV) operator.

class bdkpython.bdk.TxBuilderProtocol(*args, **kwargs)[source]

Bases: Protocol

A TxBuilder is created by calling build_tx on a wallet. After assigning it, you set options on it until finally calling finish to consume the builder and generate the transaction.

add_data(data: bytes)[source]

Add data as an output using OP_RETURN.

add_global_xpubs()[source]

Fill-in the PSBT_GLOBAL_XPUB field with the extended keys contained in both the external and internal descriptors.

This is useful for offline signers that take part to a multisig. Some hardware wallets like BitBox and ColdCard are known to require this.

add_recipient(script: Script, amount: Amount)[source]

Add a recipient to the internal list of recipients.

add_unspendable(unspendable: OutPoint)[source]

Add a utxo to the internal list of unspendable utxos.

It’s important to note that the “must-be-spent” utxos added with TxBuilder::add_utxo have priority over this.

add_utxo(outpoint: OutPoint)[source]

Add a utxo to the internal list of utxos that must be spent.

These have priority over the “unspendable” utxos, meaning that if a utxo is present both in the “utxos” and the “unspendable” list, it will be spent.

add_utxos(outpoints: List[OutPoint])[source]

Add the list of outpoints to the internal list of UTXOs that must be spent.

allow_dust(allow_dust: bool)[source]

Set whether or not the dust limit is checked.

Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.

change_policy(change_policy: ChangeSpendPolicy)[source]

Set a specific ChangeSpendPolicy. See TxBuilder::do_not_spend_change and TxBuilder::only_spend_change for some shortcuts. This method assumes the presence of an internal keychain, otherwise it has no effect.

current_height(height: int)[source]

Set the current blockchain height.

This will be used to:

1. Set the nLockTime for preventing fee sniping. Note: This will be ignored if you manually specify a nlocktime using TxBuilder::nlocktime.

2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at current_height, we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs, manually add them using TxBuilder::add_utxos. In both cases, if you don’t provide a current height, we use the last sync height.

do_not_spend_change()[source]

Do not spend change outputs.

This effectively adds all the change outputs to the “unspendable” list. See TxBuilder::unspendable. This method assumes the presence of an internal keychain, otherwise it has no effect.

drain_to(script: Script)[source]

Sets the address to drain excess coins to.

Usually, when there are excess coins they are sent to a change address generated by the wallet. This option replaces the usual change address with an arbitrary script_pubkey of your choosing. Just as with a change output, if the drain output is not needed (the excess coins are too small) it will not be included in the resulting transaction. The only difference is that it is valid to use drain_to without setting any ordinary recipients with add_recipient (but it is perfectly fine to add recipients as well).

If you choose not to set any recipients, you should provide the utxos that the transaction should spend via add_utxos. drain_to is very useful for draining all the coins in a wallet with drain_wallet to a single address.

drain_wallet()[source]

Spend all the available inputs. This respects filters like TxBuilder::unspendable and the change policy.

exclude_below_confirmations(min_confirms: int)[source]

Excludes any outpoints whose enclosing transaction has fewer than min_confirms confirmations.

min_confirms is the minimum number of confirmations a transaction must have in order for its outpoints to remain spendable. - Passing 0 will include all transactions (no filtering). - Passing 1 will exclude all unconfirmed transactions (equivalent to exclude_unconfirmed). - Passing 6 will only allow outpoints from transactions with at least 6 confirmations.

If you chain this with other filtering methods, the final set of unspendable outpoints will be the union of all filters.

exclude_unconfirmed()[source]

Exclude outpoints whose enclosing transaction is unconfirmed. This is a shorthand for exclude_below_confirmations(1).

fee_absolute(fee_amount: Amount)[source]

Set an absolute fee The fee_absolute method refers to the absolute transaction fee in Amount. If anyone sets both the fee_absolute method and the fee_rate method, the FeePolicy enum will be set by whichever method was called last, as the FeeRate and FeeAmount are mutually exclusive.

Note that this is really a minimum absolute fee – it’s possible to overshoot it slightly since adding a change output to drain the remaining excess might not be viable.

fee_rate(fee_rate: FeeRate)[source]

Set a custom fee rate.

This method sets the mining fee paid by the transaction as a rate on its size. This means that the total fee paid is equal to fee_rate times the size of the transaction. Default is 1 sat/vB in accordance with Bitcoin Core’s default relay policy.

Note that this is really a minimum feerate – it’s possible to overshoot it slightly since adding a change output to drain the remaining excess might not be viable.

finish(wallet: Wallet)[source]

Finish building the transaction.

Uses the thread-local random number generator (rng).

Returns a new Psbt per BIP174.

WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See Wallet::reveal_next_address.

manually_selected_only()[source]

Only spend utxos added by TxBuilder::add_utxo.

The wallet will not add additional utxos to the transaction even if they are needed to make the transaction valid.

nlocktime(locktime: LockTime)[source]

Use a specific nLockTime while creating the transaction.

This can cause conflicts if the wallet’s descriptors contain an “after” (OP_CLTV) operator.

only_spend_change()[source]

Only spend change outputs.

This effectively adds all the non-change outputs to the “unspendable” list. See TxBuilder::unspendable. This method assumes the presence of an internal keychain, otherwise it has no effect.

policy_path(policy_path: dict[str, List[int]], keychain: KeychainKind)[source]

The TxBuilder::policy_path is a complex API. See the Rust docs for complete information: https://docs.rs/bdk_wallet/latest/bdk_wallet/struct.TxBuilder.html#method.policy_path

set_exact_sequence(nsequence: int)[source]

Set an exact nSequence value.

This can cause conflicts if the wallet’s descriptors contain an “older” (OP_CSV) operator and the given nsequence is lower than the CSV value.

set_recipients(recipients: List[ScriptAmount])[source]

Replace the recipients already added with a new list of recipients.

unspendable(unspendable: List[OutPoint])[source]

Replace the internal list of unspendable utxos with a new list.

It’s important to note that the “must-be-spent” utxos added with TxBuilder::add_utxo have priority over these.

version(version: int)[source]

Build a transaction with a specific version.

The version should always be greater than 0 and greater than 1 if the wallet’s descriptors contain an “older” (OP_CSV) operator.

class bdkpython.bdk.TxDetails(*, txid: Txid, sent: Amount, received: Amount, fee: Amount | None, fee_rate: float | None, balance_delta: int, chain_position: ChainPosition, tx: Transaction)[source]

Bases: object

balance_delta: int
chain_position: ChainPosition
fee: Amount | None
fee_rate: float | None
received: Amount
sent: Amount
tx: Transaction
txid: Txid
class bdkpython.bdk.TxGraphChangeSet(*, txs: List[Transaction], txouts: dict[HashableOutPoint, TxOut], anchors: List[Anchor], last_seen: dict[Txid, int], first_seen: dict[Txid, int], last_evicted: dict[Txid, int])[source]

Bases: object

anchors: List[Anchor]
first_seen: dict[Txid, int]
last_evicted: dict[Txid, int]
last_seen: dict[Txid, int]
txouts: dict[HashableOutPoint, TxOut]
txs: List[Transaction]
class bdkpython.bdk.TxIn(*, previous_output: OutPoint, script_sig: Script, sequence: int, witness: List[bytes])[source]

Bases: object

A transcation input.

previous_output: OutPoint

A pointer to the previous output this input spends from.

script_sig: Script

The script corresponding to the scriptPubKey, empty in SegWit transactions.

sequence: int

https://bitcoin.stackexchange.com/questions/87372/what-does-the-sequence-in-a-transaction-input-mean

witness: List[bytes]

A proof for the script that authorizes the spend of the output.

class bdkpython.bdk.TxMerkleNode(*args, **kwargs)[source]

Bases: object

The merkle root of the merkle tree corresponding to a block’s transactions.

classmethod from_bytes(bytes: bytes)[source]

Construct a hash-like type from 32 bytes.

classmethod from_string(hex: str)[source]

Construct a hash-like type from a hex string.

serialize() bytes[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.TxMerkleNodeProtocol(*args, **kwargs)[source]

Bases: Protocol

The merkle root of the merkle tree corresponding to a block’s transactions.

serialize()[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.TxOut(*, value: Amount, script_pubkey: Script)[source]

Bases: object

Bitcoin transaction output.

Defines new coins to be created as a result of the transaction, along with spending conditions (“script”, aka “output script”), which an input spending it must satisfy.

An output that is not yet spent by an input is called Unspent Transaction Output (“UTXO”).

script_pubkey: Script

The script which must be satisfied for the output to be spent.

value: Amount

The value of the output, in satoshis.

class bdkpython.bdk.TxStatus(*, confirmed: bool, block_height: int | None, block_hash: BlockHash | None, block_time: int | None)[source]

Bases: object

Transaction confirmation metadata.

block_hash: BlockHash | None

Hash of the block.

block_height: int | None

Height of the block this transaction was included.

block_time: int | None

The time shown in the block, not necessarily the same time as when the block was found.

confirmed: bool

Is the transaction in a block.

class bdkpython.bdk.Txid(*args, **kwargs)[source]

Bases: object

A bitcoin transaction identifier

classmethod from_bytes(bytes: bytes)[source]

Construct a hash-like type from 32 bytes.

classmethod from_string(hex: str)[source]

Construct a hash-like type from a hex string.

serialize() bytes[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.TxidParseError[source]

Bases: Exception

exception InvalidTxid(txid)[source]

Bases: TxidParseError

class bdkpython.bdk.TxidProtocol(*args, **kwargs)[source]

Bases: Protocol

A bitcoin transaction identifier

serialize()[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.UnconfirmedTx(*, tx: Transaction, last_seen: int)[source]

Bases: object

This type replaces the Rust tuple (tx, last_seen) used in the Wallet::apply_unconfirmed_txs` method, where last_seen is the timestamp of when the transaction tx was last seen in the mempool.

last_seen: int
tx: Transaction
class bdkpython.bdk.Update(*args, **kwargs)[source]

Bases: object

An update for a wallet containing chain, descriptor index, and transaction data.

class bdkpython.bdk.UpdateProtocol(*args, **kwargs)[source]

Bases: Protocol

An update for a wallet containing chain, descriptor index, and transaction data.

class bdkpython.bdk.Wallet(descriptor: ~bdkpython.bdk.Descriptor, change_descriptor: ~bdkpython.bdk.Descriptor, network: ~bdkpython.bdk.Network, persister: ~bdkpython.bdk.Persister, lookahead: object | int = <object object>)[source]

Bases: object

A Bitcoin wallet.

The Wallet acts as a way of coherently interfacing with output descriptors and related transactions. Its main components are: 1. output descriptors from which it can derive addresses. 2. signers that can contribute signatures to addresses instantiated from the descriptors.

The user is responsible for loading and writing wallet changes which are represented as ChangeSets (see take_staged). Also see individual functions and example for instructions on when Wallet state needs to be persisted.

The Wallet descriptor (external) and change descriptor (internal) must not derive the same script pubkeys. See KeychainTxOutIndex::insert_descriptor() for more details.

apply_evicted_txs(evicted_txs: List[EvictedTx]) None[source]

Apply transactions that have been evicted from the mempool. Transactions may be evicted for paying too-low fee, or for being malformed. Irrelevant transactions are ignored.

For more information: https://docs.rs/bdk_wallet/latest/bdk_wallet/struct.Wallet.html#method.apply_evicted_txs

apply_unconfirmed_txs(unconfirmed_txs: List[UnconfirmedTx]) None[source]

Apply relevant unconfirmed transactions to the wallet. Transactions that are not relevant are filtered out.

apply_update(update: Update) None[source]

Applies an update to the wallet and stages the changes (but does not persist them).

Usually you create an update by interacting with some blockchain data source and inserting transactions related to your wallet into it.

After applying updates you should persist the staged wallet changes. For an example of how to persist staged wallet changes see [Wallet::reveal_next_address].

balance() Balance[source]

Return the balance, separated into available, trusted-pending, untrusted-pending and immature values.

calculate_fee(tx: Transaction) Amount[source]

Calculates the fee of a given transaction. Returns [Amount::ZERO] if tx is a coinbase transaction.

To calculate the fee for a [Transaction] with inputs not owned by this wallet you must manually insert the TxOut(s) into the tx graph using the [insert_txout] function.

Note tx does not have to be in the graph for this to work.

calculate_fee_rate(tx: Transaction) FeeRate[source]

Calculate the [FeeRate] for a given transaction.

To calculate the fee rate for a [Transaction] with inputs not owned by this wallet you must manually insert the TxOut(s) into the tx graph using the [insert_txout] function.

Note tx does not have to be in the graph for this to work.

cancel_tx(tx: Transaction) None[source]

Informs the wallet that you no longer intend to broadcast a tx that was built from it.

This frees up the change address used when creating the tx for use in future transactions.

classmethod create_from_two_path_descriptor(two_path_descriptor: ~bdkpython.bdk.Descriptor, network: ~bdkpython.bdk.Network, persister: ~bdkpython.bdk.Persister, lookahead: object | int = <object object>)[source]

Build a new Wallet from a two-path descriptor.

This function parses a multipath descriptor with exactly 2 paths and creates a wallet using the existing receive and change wallet creation logic.

Multipath descriptors follow [BIP-389](https://github.com/bitcoin/bips/blob/master/bip-0389.mediawiki) and allow defining both receive and change derivation paths in a single descriptor using the <0;1> syntax.

If you have previously created a wallet, use load instead.

Returns an error if the descriptor is invalid or not a 2-path multipath descriptor.

classmethod create_single(descriptor: ~bdkpython.bdk.Descriptor, network: ~bdkpython.bdk.Network, persister: ~bdkpython.bdk.Persister, lookahead: object | int = <object object>)[source]

Build a new single descriptor Wallet.

If you have previously created a wallet, use Wallet::load instead.

# Note

Only use this method when creating a wallet designed to be used with a single descriptor and keychain. Otherwise the recommended way to construct a new wallet is by using Wallet::new. It’s worth noting that not all features are available with single descriptor wallets, for example setting a change_policy on TxBuilder and related methods such as do_not_spend_change. This is because all payments are received on the external keychain (including change), and without a change keychain BDK lacks enough information to distinguish between change and outside payments.

Additionally because this wallet has no internal (change) keychain, all methods that require a KeychainKind as input, e.g. reveal_next_address should only be called using the External variant. In most cases passing Internal is treated as the equivalent of External but this behavior must not be relied on.

derivation_index(keychain: KeychainKind) int | None[source]

The derivation index of this wallet. It will return None if it has not derived any addresses. Otherwise, it will return the index of the highest address it has derived.

derivation_of_spk(spk: Script) KeychainAndIndex | None[source]

Finds how the wallet derived the script pubkey spk.

Will only return Some(_) if the wallet has given out the spk.

descriptor_checksum(keychain: KeychainKind) str[source]

Return the checksum of the public descriptor associated to keychain.

Internally calls [Self::public_descriptor] to fetch the right descriptor.

finalize_psbt(psbt: ~bdkpython.bdk.Psbt, sign_options: object | ~bdkpython.bdk.SignOptions | None = <object object>) bool[source]

Finalize a PSBT, i.e., for each input determine if sufficient data is available to pass validation and construct the respective scriptSig or scriptWitness. Please refer to [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#Input_Finalizer), and [BIP371](https://github.com/bitcoin/bips/blob/master/bip-0371.mediawiki) for further information.

Returns true if the PSBT could be finalized, and false otherwise.

The [SignOptions] can be used to tweak the behavior of the finalizer.

get_tx(txid: Txid) CanonicalTx | None[source]

Get a single transaction from the wallet as a [WalletTx] (if the transaction exists).

WalletTx contains the full transaction alongside meta-data such as: * Blocks that the transaction is [Anchor]ed in. These may or may not be blocks that exist in the best chain. * The [ChainPosition] of the transaction in the best chain - whether the transaction is confirmed or unconfirmed. If the transaction is confirmed, the anchor which proves the confirmation is provided. If the transaction is unconfirmed, the unix timestamp of when the transaction was last seen in the mempool is provided.

get_utxo(op: OutPoint) LocalOutput | None[source]

Returns the utxo owned by this wallet corresponding to outpoint if it exists in the wallet’s database.

insert_txout(outpoint: OutPoint, txout: TxOut) None[source]

Inserts a [TxOut] at [OutPoint] into the wallet’s transaction graph.

This is used for providing a previous output’s value so that we can use [calculate_fee] or [calculate_fee_rate] on a given transaction. Outputs inserted with this method will not be returned in [list_unspent] or [list_output].

WARNINGS: This should only be used to add `TxOut`s that the wallet does not own. Only insert `TxOut`s that you trust the values for!

You must persist the changes resulting from one or more calls to this method if you need the inserted TxOut data to be reloaded after closing the wallet. See [Wallet::reveal_next_address].

[calculate_fee]: Self::calculate_fee [calculate_fee_rate]: Self::calculate_fee_rate [list_unspent]: Self::list_unspent [list_output]: Self::list_output

is_mine(script: Script) bool[source]

Return whether or not a script is part of this wallet (either internal or external).

latest_checkpoint() BlockId[source]

Returns the latest checkpoint.

list_output() List[LocalOutput][source]

List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).

To list only unspent outputs (UTXOs), use [Wallet::list_unspent] instead.

list_unspent() List[LocalOutput][source]

Return the list of unspent outputs of this wallet.

list_unused_addresses(keychain: KeychainKind) List[AddressInfo][source]

List addresses that are revealed but unused.

Note if the returned iterator is empty you can reveal more addresses by using [reveal_next_address](Self::reveal_next_address) or [reveal_addresses_to](Self::reveal_addresses_to).

classmethod load(descriptor: ~bdkpython.bdk.Descriptor, change_descriptor: ~bdkpython.bdk.Descriptor, persister: ~bdkpython.bdk.Persister, lookahead: object | int = <object object>)[source]

Build Wallet by loading from persistence.

Note that the descriptor secret keys are not persisted to the db.

classmethod load_single(descriptor: ~bdkpython.bdk.Descriptor, persister: ~bdkpython.bdk.Persister, lookahead: object | int = <object object>)[source]

Build a single-descriptor Wallet by loading from persistence.

Note that the descriptor secret keys are not persisted to the db.

mark_used(keychain: KeychainKind, index: int) bool[source]

Marks an address used of the given keychain at index.

Returns whether the given index was present and then removed from the unused set.

network() Network[source]

Get the Bitcoin network the wallet is using.

next_derivation_index(keychain: KeychainKind) int[source]

The index of the next address that you would get if you were to ask the wallet for a new address.

next_unused_address(keychain: KeychainKind) AddressInfo[source]

Get the next unused address for the given keychain, i.e. the address with the lowest derivation index that hasn’t been used in a transaction.

This will attempt to reveal a new address if all previously revealed addresses have been used, in which case the returned address will be the same as calling [Wallet::reveal_next_address].

WARNING: To avoid address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See [Wallet::reveal_next_address].

peek_address(keychain: KeychainKind, index: int) AddressInfo[source]

Peek an address of the given keychain at index without revealing it.

For non-wildcard descriptors this returns the same address at every provided index.

# Panics

This panics when the caller requests for an address of derivation index greater than the [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) max index.

persist(persister: Persister) bool[source]

Persist staged changes of wallet into persister.

Returns whether any new changes were persisted.

If the persister errors, the staged changes will not be cleared.

policies(keychain: KeychainKind) Policy | None[source]

Return the spending policies for the wallet’s descriptor.

public_descriptor(keychain: KeychainKind) str[source]

Returns the descriptor used to create addresses for a particular keychain.

It’s the “public” version of the wallet’s descriptor, meaning a new descriptor that has the same structure but with the all secret keys replaced by their corresponding public key. This can be used to build a watch-only version of a wallet.

reveal_addresses_to(keychain: KeychainKind, index: int) List[AddressInfo][source]

Reveal addresses up to and including the target index and return an iterator of newly revealed addresses.

If the target index is unreachable, we make a best effort to reveal up to the last possible index. If all addresses up to the given index are already revealed, then no new addresses are returned.

WARNING: To avoid address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See [Wallet::reveal_next_address].

reveal_next_address(keychain: KeychainKind) AddressInfo[source]

Attempt to reveal the next address of the given keychain.

This will increment the keychain’s derivation index. If the keychain’s descriptor doesn’t contain a wildcard or every address is already revealed up to the maximum derivation index defined in [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), then the last revealed address will be returned.

sent_and_received(tx: Transaction) SentAndReceivedValues[source]

Compute the tx’s sent and received [Amount]s.

This method returns a tuple (sent, received). Sent is the sum of the txin amounts that spend from previous txouts tracked by this wallet. Received is the summation of this tx’s outputs that send to script pubkeys tracked by this wallet.

sign(psbt: ~bdkpython.bdk.Psbt, sign_options: object | ~bdkpython.bdk.SignOptions | None = <object object>) bool[source]

Sign a transaction with all the wallet’s signers, in the order specified by every signer’s [SignerOrdering]. This function returns the Result type with an encapsulated bool that has the value true if the PSBT was finalized, or false otherwise.

The [SignOptions] can be used to tweak the behavior of the software signers, and the way the transaction is finalized at the end. Note that it can’t be guaranteed that every signers will follow the options, but the “software signers” (WIF keys and xprv) defined in this library will.

staged() ChangeSet | None[source]

Get a reference of the staged [ChangeSet] that is yet to be committed (if any).

start_full_scan() FullScanRequestBuilder[source]

Create a [`FullScanRequest] for this wallet.

This is the first step when performing a spk-based wallet full scan, the returned [`FullScanRequest] collects iterators for the wallet’s keychain script pub keys needed to start a blockchain full scan with a spk based blockchain client.

This operation is generally only used when importing or restoring a previously used wallet in which the list of used scripts is not known.

start_sync_with_revealed_spks() SyncRequestBuilder[source]

Create a partial [SyncRequest] for this wallet for all revealed spks.

This is the first step when performing a spk-based wallet partial sync, the returned [SyncRequest] collects all revealed script pubkeys from the wallet keychain needed to start a blockchain sync with a spk based blockchain client.

take_staged() ChangeSet | None[source]

Take the staged [ChangeSet] to be persisted now (if any).

transactions() List[CanonicalTx][source]

Iterate over the transactions in the wallet.

tx_details(txid: Txid) TxDetails | None[source]

Get the [TxDetails] of a wallet transaction.

unmark_used(keychain: KeychainKind, index: int) bool[source]

Undoes the effect of [mark_used] and returns whether the index was inserted back into the unused set.

Since this is only a superficial marker, it will have no effect if the address at the given index was actually used, i.e. the wallet has previously indexed a tx output for the derived spk.

[mark_used]: Self::mark_used

class bdkpython.bdk.WalletProtocol(*args, **kwargs)[source]

Bases: Protocol

A Bitcoin wallet.

The Wallet acts as a way of coherently interfacing with output descriptors and related transactions. Its main components are: 1. output descriptors from which it can derive addresses. 2. signers that can contribute signatures to addresses instantiated from the descriptors.

The user is responsible for loading and writing wallet changes which are represented as ChangeSets (see take_staged). Also see individual functions and example for instructions on when Wallet state needs to be persisted.

The Wallet descriptor (external) and change descriptor (internal) must not derive the same script pubkeys. See KeychainTxOutIndex::insert_descriptor() for more details.

apply_evicted_txs(evicted_txs: List[EvictedTx])[source]

Apply transactions that have been evicted from the mempool. Transactions may be evicted for paying too-low fee, or for being malformed. Irrelevant transactions are ignored.

For more information: https://docs.rs/bdk_wallet/latest/bdk_wallet/struct.Wallet.html#method.apply_evicted_txs

apply_unconfirmed_txs(unconfirmed_txs: List[UnconfirmedTx])[source]

Apply relevant unconfirmed transactions to the wallet. Transactions that are not relevant are filtered out.

apply_update(update: Update)[source]

Applies an update to the wallet and stages the changes (but does not persist them).

Usually you create an update by interacting with some blockchain data source and inserting transactions related to your wallet into it.

After applying updates you should persist the staged wallet changes. For an example of how to persist staged wallet changes see [Wallet::reveal_next_address].

balance()[source]

Return the balance, separated into available, trusted-pending, untrusted-pending and immature values.

calculate_fee(tx: Transaction)[source]

Calculates the fee of a given transaction. Returns [Amount::ZERO] if tx is a coinbase transaction.

To calculate the fee for a [Transaction] with inputs not owned by this wallet you must manually insert the TxOut(s) into the tx graph using the [insert_txout] function.

Note tx does not have to be in the graph for this to work.

calculate_fee_rate(tx: Transaction)[source]

Calculate the [FeeRate] for a given transaction.

To calculate the fee rate for a [Transaction] with inputs not owned by this wallet you must manually insert the TxOut(s) into the tx graph using the [insert_txout] function.

Note tx does not have to be in the graph for this to work.

cancel_tx(tx: Transaction)[source]

Informs the wallet that you no longer intend to broadcast a tx that was built from it.

This frees up the change address used when creating the tx for use in future transactions.

derivation_index(keychain: KeychainKind)[source]

The derivation index of this wallet. It will return None if it has not derived any addresses. Otherwise, it will return the index of the highest address it has derived.

derivation_of_spk(spk: Script)[source]

Finds how the wallet derived the script pubkey spk.

Will only return Some(_) if the wallet has given out the spk.

descriptor_checksum(keychain: KeychainKind)[source]

Return the checksum of the public descriptor associated to keychain.

Internally calls [Self::public_descriptor] to fetch the right descriptor.

finalize_psbt(psbt: ~bdkpython.bdk.Psbt, sign_options: object | ~bdkpython.bdk.SignOptions | None = <object object>)[source]

Finalize a PSBT, i.e., for each input determine if sufficient data is available to pass validation and construct the respective scriptSig or scriptWitness. Please refer to [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#Input_Finalizer), and [BIP371](https://github.com/bitcoin/bips/blob/master/bip-0371.mediawiki) for further information.

Returns true if the PSBT could be finalized, and false otherwise.

The [SignOptions] can be used to tweak the behavior of the finalizer.

get_tx(txid: Txid)[source]

Get a single transaction from the wallet as a [WalletTx] (if the transaction exists).

WalletTx contains the full transaction alongside meta-data such as: * Blocks that the transaction is [Anchor]ed in. These may or may not be blocks that exist in the best chain. * The [ChainPosition] of the transaction in the best chain - whether the transaction is confirmed or unconfirmed. If the transaction is confirmed, the anchor which proves the confirmation is provided. If the transaction is unconfirmed, the unix timestamp of when the transaction was last seen in the mempool is provided.

get_utxo(op: OutPoint)[source]

Returns the utxo owned by this wallet corresponding to outpoint if it exists in the wallet’s database.

insert_txout(outpoint: OutPoint, txout: TxOut)[source]

Inserts a [TxOut] at [OutPoint] into the wallet’s transaction graph.

This is used for providing a previous output’s value so that we can use [calculate_fee] or [calculate_fee_rate] on a given transaction. Outputs inserted with this method will not be returned in [list_unspent] or [list_output].

WARNINGS: This should only be used to add `TxOut`s that the wallet does not own. Only insert `TxOut`s that you trust the values for!

You must persist the changes resulting from one or more calls to this method if you need the inserted TxOut data to be reloaded after closing the wallet. See [Wallet::reveal_next_address].

[calculate_fee]: Self::calculate_fee [calculate_fee_rate]: Self::calculate_fee_rate [list_unspent]: Self::list_unspent [list_output]: Self::list_output

is_mine(script: Script)[source]

Return whether or not a script is part of this wallet (either internal or external).

latest_checkpoint()[source]

Returns the latest checkpoint.

list_output()[source]

List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).

To list only unspent outputs (UTXOs), use [Wallet::list_unspent] instead.

list_unspent()[source]

Return the list of unspent outputs of this wallet.

list_unused_addresses(keychain: KeychainKind)[source]

List addresses that are revealed but unused.

Note if the returned iterator is empty you can reveal more addresses by using [reveal_next_address](Self::reveal_next_address) or [reveal_addresses_to](Self::reveal_addresses_to).

mark_used(keychain: KeychainKind, index: int)[source]

Marks an address used of the given keychain at index.

Returns whether the given index was present and then removed from the unused set.

network()[source]

Get the Bitcoin network the wallet is using.

next_derivation_index(keychain: KeychainKind)[source]

The index of the next address that you would get if you were to ask the wallet for a new address.

next_unused_address(keychain: KeychainKind)[source]

Get the next unused address for the given keychain, i.e. the address with the lowest derivation index that hasn’t been used in a transaction.

This will attempt to reveal a new address if all previously revealed addresses have been used, in which case the returned address will be the same as calling [Wallet::reveal_next_address].

WARNING: To avoid address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See [Wallet::reveal_next_address].

peek_address(keychain: KeychainKind, index: int)[source]

Peek an address of the given keychain at index without revealing it.

For non-wildcard descriptors this returns the same address at every provided index.

# Panics

This panics when the caller requests for an address of derivation index greater than the [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) max index.

persist(persister: Persister)[source]

Persist staged changes of wallet into persister.

Returns whether any new changes were persisted.

If the persister errors, the staged changes will not be cleared.

policies(keychain: KeychainKind)[source]

Return the spending policies for the wallet’s descriptor.

public_descriptor(keychain: KeychainKind)[source]

Returns the descriptor used to create addresses for a particular keychain.

It’s the “public” version of the wallet’s descriptor, meaning a new descriptor that has the same structure but with the all secret keys replaced by their corresponding public key. This can be used to build a watch-only version of a wallet.

reveal_addresses_to(keychain: KeychainKind, index: int)[source]

Reveal addresses up to and including the target index and return an iterator of newly revealed addresses.

If the target index is unreachable, we make a best effort to reveal up to the last possible index. If all addresses up to the given index are already revealed, then no new addresses are returned.

WARNING: To avoid address reuse you must persist the changes resulting from one or more calls to this method before closing the wallet. See [Wallet::reveal_next_address].

reveal_next_address(keychain: KeychainKind)[source]

Attempt to reveal the next address of the given keychain.

This will increment the keychain’s derivation index. If the keychain’s descriptor doesn’t contain a wildcard or every address is already revealed up to the maximum derivation index defined in [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), then the last revealed address will be returned.

sent_and_received(tx: Transaction)[source]

Compute the tx’s sent and received [Amount]s.

This method returns a tuple (sent, received). Sent is the sum of the txin amounts that spend from previous txouts tracked by this wallet. Received is the summation of this tx’s outputs that send to script pubkeys tracked by this wallet.

sign(psbt: ~bdkpython.bdk.Psbt, sign_options: object | ~bdkpython.bdk.SignOptions | None = <object object>)[source]

Sign a transaction with all the wallet’s signers, in the order specified by every signer’s [SignerOrdering]. This function returns the Result type with an encapsulated bool that has the value true if the PSBT was finalized, or false otherwise.

The [SignOptions] can be used to tweak the behavior of the software signers, and the way the transaction is finalized at the end. Note that it can’t be guaranteed that every signers will follow the options, but the “software signers” (WIF keys and xprv) defined in this library will.

staged()[source]

Get a reference of the staged [ChangeSet] that is yet to be committed (if any).

start_full_scan()[source]

Create a [`FullScanRequest] for this wallet.

This is the first step when performing a spk-based wallet full scan, the returned [`FullScanRequest] collects iterators for the wallet’s keychain script pub keys needed to start a blockchain full scan with a spk based blockchain client.

This operation is generally only used when importing or restoring a previously used wallet in which the list of used scripts is not known.

start_sync_with_revealed_spks()[source]

Create a partial [SyncRequest] for this wallet for all revealed spks.

This is the first step when performing a spk-based wallet partial sync, the returned [SyncRequest] collects all revealed script pubkeys from the wallet keychain needed to start a blockchain sync with a spk based blockchain client.

take_staged()[source]

Take the staged [ChangeSet] to be persisted now (if any).

transactions()[source]

Iterate over the transactions in the wallet.

tx_details(txid: Txid)[source]

Get the [TxDetails] of a wallet transaction.

unmark_used(keychain: KeychainKind, index: int)[source]

Undoes the effect of [mark_used] and returns whether the index was inserted back into the unused set.

Since this is only a superficial marker, it will have no effect if the address at the given index was actually used, i.e. the wallet has previously indexed a tx output for the derived spk.

[mark_used]: Self::mark_used

class bdkpython.bdk.Warning[source]

Bases: object

Warnings a node may issue while running.

COULD_NOT_CONNECT[source]

alias of COULD_NOT_CONNECT

EVALUATING_FORK[source]

alias of EVALUATING_FORK

NEED_CONNECTIONS[source]

alias of NEED_CONNECTIONS

NO_COMPACT_FILTERS[source]

alias of NO_COMPACT_FILTERS

PEER_TIMED_OUT[source]

alias of PEER_TIMED_OUT

POTENTIAL_STALE_TIP[source]

alias of POTENTIAL_STALE_TIP

REQUEST_FAILED[source]

alias of REQUEST_FAILED

TRANSACTION_REJECTED[source]

alias of TRANSACTION_REJECTED

UNEXPECTED_SYNC_ERROR[source]

alias of UNEXPECTED_SYNC_ERROR

UNSOLICITED_MESSAGE[source]

alias of UNSOLICITED_MESSAGE

is_COULD_NOT_CONNECT() bool[source]
is_EVALUATING_FORK() bool[source]
is_NEED_CONNECTIONS() bool[source]
is_NO_COMPACT_FILTERS() bool[source]
is_PEER_TIMED_OUT() bool[source]
is_POTENTIAL_STALE_TIP() bool[source]
is_REQUEST_FAILED() bool[source]
is_TRANSACTION_REJECTED() bool[source]
is_UNEXPECTED_SYNC_ERROR() bool[source]
is_UNSOLICITED_MESSAGE() bool[source]
is_could_not_connect() bool[source]
is_evaluating_fork() bool[source]
is_need_connections() bool[source]
is_no_compact_filters() bool[source]
is_peer_timed_out() bool[source]
is_potential_stale_tip() bool[source]
is_request_failed() bool[source]
is_transaction_rejected() bool[source]
is_unexpected_sync_error() bool[source]
is_unsolicited_message() bool[source]
class bdkpython.bdk.WitnessProgram(*, version: int, program: bytes)[source]

Bases: object

The version and program of a Segwit address.

program: bytes

The witness program.

version: int

Version. For example 1 for Taproot.

class bdkpython.bdk.WordCount(*values)[source]

Bases: Enum

WORDS12 = 0
WORDS15 = 1
WORDS18 = 2
WORDS21 = 3
WORDS24 = 4
class bdkpython.bdk.Wtxid(*args, **kwargs)[source]

Bases: object

A bitcoin transaction identifier, including witness data. For transactions with no SegWit inputs, the txid will be equivalent to wtxid.

classmethod from_bytes(bytes: bytes)[source]

Construct a hash-like type from 32 bytes.

classmethod from_string(hex: str)[source]

Construct a hash-like type from a hex string.

serialize() bytes[source]

Serialize this type into a 32 byte array.

class bdkpython.bdk.WtxidProtocol(*args, **kwargs)[source]

Bases: Protocol

A bitcoin transaction identifier, including witness data. For transactions with no SegWit inputs, the txid will be equivalent to wtxid.

serialize()[source]

Serialize this type into a 32 byte array.