API Reference
- class bdkpython.bdk.Address(address: str, network: Network)[source]
Bases:
objectA bitcoin address
- classmethod from_script(script: Script, network: Network)[source]
Parse a script as an address for the given network
- to_address_data() AddressData[source]
Return the data for the address.
- class bdkpython.bdk.AddressInfo(*, index: int, address: Address, keychain: KeychainKind)[source]
Bases:
objectA derived address and the index it was found at.
- 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.Amount(*args, **kwargs)[source]
Bases:
objectThe 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_sat(satoshi: int)[source]
Create an Amount with satoshi precision and the given number of satoshis.
- class bdkpython.bdk.AmountProtocol(*args, **kwargs)[source]
Bases:
ProtocolThe 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.
- class bdkpython.bdk.Anchor(*, confirmation_block_time: ConfirmationBlockTime, txid: Txid)[source]
Bases:
object- confirmation_block_time: ConfirmationBlockTime
- class bdkpython.bdk.Balance(*, immature: Amount, trusted_pending: Amount, untrusted_pending: Amount, confirmed: Amount, trusted_spendable: Amount, total: Amount)[source]
Bases:
objectBalance, differentiated into various categories.
- 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.BlockHashProtocol(*args, **kwargs)[source]
Bases:
ProtocolA bitcoin Block hash
- class bdkpython.bdk.BlockId(*, height: int, hash: BlockHash)[source]
Bases:
objectA reference to a block in the canonical chain.
- height: int
The height of the block.
- class bdkpython.bdk.BumpFeeTxBuilder(txid: Txid, fee_rate: FeeRate)[source]
Bases:
objectA 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:
ProtocolA 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.
- 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:
objectA 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:
objectBuild 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:
ProtocolBuild 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.
- 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.
- 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:
objectA [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.
- 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.
- class bdkpython.bdk.CbfClientProtocol(*args, **kwargs)[source]
Bases:
ProtocolA [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.
- 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.
- class bdkpython.bdk.CbfComponents(*, client: CbfClient, node: CbfNode)[source]
Bases:
objectReceive a [CbfClient] and [CbfNode].
- class bdkpython.bdk.CbfNode(*args, **kwargs)[source]
Bases:
objectA [CbfNode] gathers transactions for a [Wallet]. To receive [Update] for [Wallet], refer to the [CbfClient]. The [CbfNode] will run until instructed to stop.
- class bdkpython.bdk.CbfNodeProtocol(*args, **kwargs)[source]
Bases:
ProtocolA [CbfNode] gathers transactions for a [Wallet]. To receive [Update] for [Wallet], refer to the [CbfClient]. The [CbfNode] will run until instructed to stop.
- class bdkpython.bdk.ChainChange(*, height: int, hash: BlockHash | None)[source]
Bases:
objectThe hash added or removed at the given height.
- height: int
Effected height
- class bdkpython.bdk.ChainPosition[source]
Bases:
objectRepresents the observed position of some chain data.
- UNCONFIRMED[source]
alias of
UNCONFIRMED
- 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.
- tx_graph_changeset() TxGraphChangeSet[source]
Get the changes to the transaction graph.
- class bdkpython.bdk.ChangeSpendPolicy(*values)[source]
Bases:
EnumPolicy 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:
objectAn extra condition that must be satisfied but that is out of control of the user
- csv: int | None
Optional CheckSequenceVerify condition
- class bdkpython.bdk.ConfirmationBlockTime(*, block_id: BlockId, confirmation_time: int)[source]
Bases:
objectRepresents the confirmation block and time of a transaction.
- 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:
objectA BIP-32 derivation path.
- class bdkpython.bdk.DerivationPathProtocol(*args, **kwargs)[source]
Bases:
ProtocolA BIP-32 derivation path.
- class bdkpython.bdk.Descriptor(descriptor: str, network: Network)[source]
Bases:
objectAn 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.
- 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:
objectA collision-proof unique identifier for a descriptor.
- class bdkpython.bdk.DescriptorIdProtocol(*args, **kwargs)[source]
Bases:
ProtocolA collision-proof unique identifier for a descriptor.
- 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:
ProtocolAn expression of how to derive output scripts: https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md
- is_multipath()[source]
Does this descriptor contain paths: https://github.com/bitcoin/bips/blob/master/bip-0389.mediawiki
- class bdkpython.bdk.DescriptorPublicKey(*args, **kwargs)[source]
Bases:
objectA 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.
- class bdkpython.bdk.DescriptorPublicKeyProtocol(*args, **kwargs)[source]
Bases:
ProtocolA 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.
- class bdkpython.bdk.DescriptorSecretKey(network: Network, mnemonic: Mnemonic, password: str | None)[source]
Bases:
objectA 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.
- class bdkpython.bdk.DescriptorSecretKeyProtocol(*args, **kwargs)[source]
Bases:
ProtocolA descriptor containing secret data.
- 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.
- class bdkpython.bdk.DescriptorType(*values)[source]
Bases:
EnumDescriptor 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:
objectWrapper 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.
- 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:
ProtocolWrapper 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.
- 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
Bases:
ElectrumError
- class bdkpython.bdk.EsploraClient(url: str, proxy: object | str | None = <object object>)[source]
Bases:
objectWrapper 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_tx(txid: Txid) Transaction | None[source]
Get a [Transaction] option 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:
ProtocolWrapper 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_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).
- 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:
objectThis 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
- 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:
objectRepresents 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.
- class bdkpython.bdk.FeeRateError[source]
Bases:
Exception- exception ArithmeticOverflow[source]
Bases:
FeeRateError
- class bdkpython.bdk.FeeRateProtocol(*args, **kwargs)[source]
Bases:
ProtocolRepresents 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.
- class bdkpython.bdk.FinalizedPsbtResult(*, psbt: Psbt, could_finalize: bool, errors: List[PsbtFinalizeError] | None)[source]
Bases:
object- could_finalize: bool
- errors: List[PsbtFinalizeError] | None
- 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.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- inspect_spks_for_all_keychains(inspector: FullScanScriptInspector)[source]
- 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:
objectAn [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.
- class bdkpython.bdk.HashableOutPointProtocol(*args, **kwargs)[source]
Bases:
ProtocolAn [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.
- class bdkpython.bdk.Header(*, version: int, prev_blockhash: BlockHash, merkle_root: TxMerkleNode, time: int, bits: int, nonce: int)[source]
Bases:
objectBitcoin 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.
- 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:
objectNotification of a new block header.
- height: int
New block height.
- class bdkpython.bdk.IndexerChangeSet(*, last_revealed: dict[DescriptorId, int])[source]
Bases:
objectMapping of descriptors to their last revealed index.
- last_revealed: dict[DescriptorId, int]
- class bdkpython.bdk.Info[source]
Bases:
objectA log message from the node.
- BLOCK_RECEIVED[source]
alias of
BLOCK_RECEIVED
- CONNECTIONS_MET[source]
alias of
CONNECTIONS_MET
- SUCCESSFUL_HANDSHAKE[source]
alias of
SUCCESSFUL_HANDSHAKE
- 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:
objectA 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.
- 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.
- class bdkpython.bdk.IpAddress(*args, **kwargs)[source]
Bases:
objectAn IP address to connect to over TCP.
- class bdkpython.bdk.IpAddressProtocol(*args, **kwargs)[source]
Bases:
ProtocolAn 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:
objectThe 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:
EnumTypes 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:
objectChanges 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:
objectAn 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
- 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:
objectA mnemonic seed phrase to recover a BIP-32 wallet.
- class bdkpython.bdk.MnemonicProtocol(*args, **kwargs)[source]
Bases:
ProtocolA mnemonic seed phrase to recover a BIP-32 wallet.
- class bdkpython.bdk.Network(*values)[source]
Bases:
EnumThe 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:
objectA reference to an unspent output by TXID and output index.
- 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:
objectA peer to connect to over the Bitcoin peer-to-peer network.
- 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:
objectDefinition of a wallet persistence implementation.
- class bdkpython.bdk.PersistenceError[source]
Bases:
Exception- exception Reason(error_message)[source]
Bases:
PersistenceError
- class bdkpython.bdk.PersistenceImpl(*args, **kwargs)[source]
Bases:
objectDefinition of a wallet persistence implementation.
- class bdkpython.bdk.PersistenceProtocol(*args, **kwargs)[source]
Bases:
ProtocolDefinition of a wallet persistence implementation.
- class bdkpython.bdk.Persister(*args, **kwargs)[source]
Bases:
objectWallet backend implementations.
- classmethod custom(persistence: Persistence)[source]
Use a native persistence layer.
- class bdkpython.bdk.PersisterProtocol(*args, **kwargs)[source]
Bases:
ProtocolWallet backend implementations.
- class bdkpython.bdk.PkOrF[source]
Bases:
object- FINGERPRINT[source]
alias of
FINGERPRINT
- X_ONLY_PUBKEY[source]
alias of
X_ONLY_PUBKEY
- class bdkpython.bdk.Policy(*args, **kwargs)[source]
Bases:
objectDescriptor spending policy
- contribution() Satisfaction[source]
- item() SatisfiableItem[source]
- satisfaction() Satisfaction[source]
- class bdkpython.bdk.PolicyProtocol(*args, **kwargs)[source]
Bases:
ProtocolDescriptor spending policy
- 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:
objectA 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_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.
- 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:
ProtocolA 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.
- 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- PARTIAL_COMPLETE[source]
alias of
PARTIAL_COMPLETE
- 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
- 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
- class bdkpython.bdk.ScanType[source]
Bases:
objectSync a wallet from the last known block hash or recover a wallet from a specified recovery point.
- class bdkpython.bdk.Script(raw_output_script: bytes)[source]
Bases:
objectA bitcoin script: https://en.bitcoin.it/wiki/Script
- class bdkpython.bdk.ScriptAmount(*, script: Script, amount: Amount)[source]
Bases:
objectA bitcoin script and associated amount.
- class bdkpython.bdk.ScriptProtocol(*args, **kwargs)[source]
Bases:
ProtocolA bitcoin script: https://en.bitcoin.it/wiki/Script
- class bdkpython.bdk.SentAndReceivedValues(*, sent: Amount, received: Amount)[source]
Bases:
objectThe total value sent and received.
- 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:
objectResponse to an ElectrumClient.server_features request.
- 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:
objectOptions 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:
objectA proxy to route network traffic, most likely through a Tor daemon. Normally this proxy is exposed at 127.0.0.1:9050.
- port: int
The listening port, likely 9050
- 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- inspect_spks(inspector: SyncScriptInspector)[source]
- class bdkpython.bdk.TapKeyOrigin(*, tap_leaf_hashes: List[str], key_source: KeySource)[source]
Bases:
object- 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
- 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:
objectBitcoin 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.
- 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
[BIP-65 OP_CHECKLOCKTIMEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki)
[BIP-113 Median time-past as endpoint for lock-time calculations](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki)
- 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.
- 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:
ProtocolBitcoin 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).
- 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
[BIP-65 OP_CHECKLOCKTIMEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki)
[BIP-113 Median time-past as endpoint for lock-time calculations](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki)
- 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.
- 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:
objectBitcoin 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.
- 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:
objectA 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_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.
- class bdkpython.bdk.TxBuilderProtocol(*args, **kwargs)[source]
Bases:
ProtocolA 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_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.
- 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_rate: float | None
- tx: Transaction
- 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- txouts: dict[HashableOutPoint, TxOut]
- txs: List[Transaction]
- class bdkpython.bdk.TxIn(*, previous_output: OutPoint, script_sig: Script, sequence: int, witness: List[bytes])[source]
Bases:
objectA transcation input.
- 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:
objectThe merkle root of the merkle tree corresponding to a block’s transactions.
- class bdkpython.bdk.TxMerkleNodeProtocol(*args, **kwargs)[source]
Bases:
ProtocolThe merkle root of the merkle tree corresponding to a block’s transactions.
- class bdkpython.bdk.TxOut(*, value: Amount, script_pubkey: Script)[source]
Bases:
objectBitcoin 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”).
- class bdkpython.bdk.TxStatus(*, confirmed: bool, block_height: int | None, block_hash: BlockHash | None, block_time: int | None)[source]
Bases:
objectTransaction confirmation metadata.
- 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.TxidParseError[source]
Bases:
Exception- exception InvalidTxid(txid)[source]
Bases:
TxidParseError
- class bdkpython.bdk.TxidProtocol(*args, **kwargs)[source]
Bases:
ProtocolA bitcoin transaction identifier
- class bdkpython.bdk.UnconfirmedTx(*, tx: Transaction, last_seen: int)[source]
Bases:
objectThis 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:
objectAn update for a wallet containing chain, descriptor index, and transaction data.
- class bdkpython.bdk.UpdateProtocol(*args, **kwargs)[source]
Bases:
ProtocolAn 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:
objectA 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).
- 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.
- 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.
- transactions() List[CanonicalTx][source]
Iterate over the transactions in the wallet.
- 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:
ProtocolA 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).
- 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_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.
- 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.
- 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.
- 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:
objectWarnings 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
- class bdkpython.bdk.WitnessProgram(*, version: int, program: bytes)[source]
Bases:
objectThe 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