Struct bdk::wallet::Wallet

source ·
pub struct Wallet<D = ()> { /* private fields */ }
Expand description

A Bitcoin wallet

The Wallet struct 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.

Implementations§

Creates a wallet that does not persist data.

Creates a wallet that does not persist data, with a custom genesis hash.

Infallibly return a derived address using the external descriptor, see AddressIndex for available address index selection strategies. If none of the keys in the descriptor are derivable (i.e. does not end with /*) then the same address will always be returned for any AddressIndex.

Infallibly return a derived address using the internal (change) descriptor.

If the wallet doesn’t have an internal descriptor it will use the external descriptor.

see AddressIndex for available address index selection strategies. If none of the keys in the descriptor are derivable (i.e. does not end with /*) then the same address will always be returned for any AddressIndex.

Initialize an empty Wallet.

Initialize an empty Wallet with a custom genesis hash.

This is like Wallet::new with an additional genesis_hash parameter. This is useful for syncing from alternative networks.

Load Wallet from the given persistence backend.

Either loads Wallet from persistence, or initializes it if it does not exist.

This method will fail if the loaded Wallet has different parameters to those provided.

Either loads Wallet from persistence, or initializes it if it does not exist (with a custom genesis hash).

This method will fail if the loaded Wallet has different parameters to those provided. This is like Wallet::new_or_load with an additional genesis_hash parameter. This is useful for syncing from alternative networks.

Get the Bitcoin network the wallet is using.

Iterator over all keychains in this wallet

Return a derived address using the external descriptor, see AddressIndex for available address index selection strategies. If none of the keys in the descriptor are derivable (i.e. does not end with /*) then the same address will always be returned for any AddressIndex.

A PersistBackend<ChangeSet>::WriteError will result if unable to persist the new address to the PersistBackend.

Return a derived address using the internal (change) descriptor.

If the wallet doesn’t have an internal descriptor it will use the external descriptor.

A PersistBackend<ChangeSet>::WriteError will result if unable to persist the new address to the PersistBackend.

see AddressIndex for available address index selection strategies. If none of the keys in the descriptor are derivable (i.e. does not end with /*) then the same address will always be returned for any AddressIndex.

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

Finds how the wallet derived the script pubkey spk.

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

Return the list of unspent outputs of this wallet

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

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

Get all the checkpoints the wallet is currently storing indexed by height.

Returns the latest checkpoint.

Returns a iterators of all the script pubkeys for the Internal and Externalvariants inKeychainKind`.

This is intended to be used when doing a full scan of your addresses (e.g. after restoring from seed words). You pass the BTreeMap of iterators to a blockchain data source (e.g. electrum server) which will go through each address until it reaches a stop gap.

Note carefully that iterators go over all script pubkeys on the keychains (not what script pubkeys the wallet is storing internally).

Gets an iterator over all the script pubkeys in a single keychain.

See spks_of_all_keychains for more documentation

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

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.

Any inserted TxOuts are not persisted until commit is called.

WARNING: This should only be used to add TxOuts that the wallet does not own. Only insert TxOuts that you trust the values for!

Calculates the fee of a given transaction. Returns 0 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.

Examples
let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
let fee = wallet.calculate_fee(tx).expect("fee");
let tx = &psbt.clone().extract_tx();
let fee = wallet.calculate_fee(tx).expect("fee");

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.

Examples
let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
let tx = &psbt.clone().extract_tx();
let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");

Computes total input value going from script pubkeys in the index (sent) and the total output value going to script pubkeys in the index (received) in tx.

For the sent to be computed correctly, the outputs being spent must have already been scanned by the index. Calculating received just uses the [Transaction] outputs directly, so it will be correct even if it has not been scanned.

Examples
let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
let (sent, received) = wallet.sent_and_received(tx);
let tx = &psbt.clone().extract_tx();
let (sent, received) = wallet.sent_and_received(tx);

Get a single transaction from the wallet as a CanonicalTx (if the transaction exists).

CanonicalTx contains the full transaction alongside meta-data such as:

  • Blocks that the transaction is Anchored 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.
use bdk::{chain::ChainPosition, Wallet};
use bdk_chain::Anchor;

let canonical_tx = wallet.get_tx(my_txid).expect("panic if tx does not exist");

// get reference to full transaction
println!("my tx: {:#?}", canonical_tx.tx_node.tx);

// list all transaction anchors
for anchor in canonical_tx.tx_node.anchors {
    println!(
        "tx is anchored by block of hash {}",
        anchor.anchor_block().hash
    );
}

// get confirmation status of transaction
match canonical_tx.chain_position {
    ChainPosition::Confirmed(anchor) => println!(
        "tx is confirmed at height {}, we know this since {}:{} is in the best chain",
        anchor.confirmation_height, anchor.anchor_block.height, anchor.anchor_block.hash,
    ),
    ChainPosition::Unconfirmed(last_seen) => println!(
        "tx is last seen at {}, it is unconfirmed as it is not anchored in the best chain",
        last_seen,
    ),
}

Add a new checkpoint to the wallet’s internal view of the chain. This stages but does not commit the change.

Returns whether anything changed with the insertion (e.g. false if checkpoint was already there).

Add a transaction to the wallet’s internal view of the chain. This stages but does not commit the change.

Returns whether anything changed with the transaction insertion (e.g. false if the transaction was already inserted at the same position).

A tx can be rejected if position has a height greater than the latest_checkpoint. Therefore you should use insert_checkpoint to insert new checkpoints before manually inserting new transactions.

WARNING: If position is confirmed, we anchor the tx to a the lowest checkpoint that is >= the position’s height. The caller is responsible for ensuring the tx exists in our local view of the best chain’s history.

Iterate over the transactions in the wallet.

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

Add an external signer

See the signer module for an example.

Get the signers

Example
let wallet = Wallet::new_no_persist("wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/0'/0'/0/*)", None, Network::Testnet)?;
for secret_key in wallet.get_signers(KeychainKind::External).signers().iter().filter_map(|s| s.descriptor_secret_key()) {
    // secret_key: tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/0'/0'/0/*
    println!("secret_key: {}", secret_key);
}

Ok::<(), Box<dyn std::error::Error>>(())

Start building a transaction.

This returns a blank TxBuilder from which you can specify the parameters for the transaction.

Example
let psbt = {
   let mut builder =  wallet.build_tx();
   builder
       .add_recipient(to_address.script_pubkey(), 50_000);
   builder.finish()?
};

// sign and broadcast ...

Bump the fee of a transaction previously created with this wallet.

Returns an error if the transaction is already confirmed or doesn’t explicitly signal replace by fee (RBF). If the transaction can be fee bumped then it returns a TxBuilder pre-populated with the inputs and outputs of the original transaction.

Example
let mut psbt = {
    let mut builder = wallet.build_tx();
    builder
        .add_recipient(to_address.script_pubkey(), 50_000)
        .enable_rbf();
    builder.finish()?
};
let _ = wallet.sign(&mut psbt, SignOptions::default())?;
let tx = psbt.extract_tx();
// broadcast tx but it's taking too long to confirm so we want to bump the fee
let mut psbt =  {
    let mut builder = wallet.build_fee_bump(tx.txid())?;
    builder
        .fee_rate(bdk::FeeRate::from_sat_per_vb(5.0));
    builder.finish()?
};

let _ = wallet.sign(&mut psbt, SignOptions::default())?;
let fee_bumped_tx = psbt.extract_tx();
// broadcast fee_bumped_tx to replace original

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.

Example
let mut psbt = {
    let mut builder = wallet.build_tx();
    builder.add_recipient(to_address.script_pubkey(), 50_000);
    builder.finish()?
};
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized, "we should have signed all the inputs");

Return the spending policies for the wallet’s descriptor

Return the “public” version of the wallet’s descriptor, meaning a new descriptor that has the same structure but with every secret key removed

This can be used to build a watch-only version of a wallet

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 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.

Return the secp256k1 context used for all signing operations

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

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.

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

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.

get the corresponding PSBT Input for a LocalUtxo

Return the checksum of the public descriptor associated to keychain

Internally calls Self::get_descriptor_for_keychain to fetch the right descriptor

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

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

Commits all currently staged changed to the persistence backend returning and error when this fails.

This returns whether the update resulted in any changes.

Returns the changes that will be staged with the next call to commit.

Get a reference to the inner TxGraph.

Get a reference to the inner KeychainTxOutIndex.

Get a reference to the inner LocalChain.

Trait Implementations§

Converts this type into a shared reference of the (usually inferred) input type.
Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.