pub struct Wallet { /* private fields */ }Expand description
A Bitcoin wallet.
The Wallet acts as a way of coherently interfacing with output descriptors and related transactions. Its main components are:
- output descriptors from which it can derive addresses.
- 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.
Implementations§
Source§impl Wallet
impl Wallet
Sourcepub fn new(
descriptor: Arc<Descriptor>,
change_descriptor: Arc<Descriptor>,
network: Network,
persister: Arc<Persister>,
lookahead: u32,
) -> Result<Self, CreateWithPersistError>
pub fn new( descriptor: Arc<Descriptor>, change_descriptor: Arc<Descriptor>, network: Network, persister: Arc<Persister>, lookahead: u32, ) -> Result<Self, CreateWithPersistError>
Build a new Wallet.
If you have previously created a wallet, use load instead.
Sourcepub fn create_single(
descriptor: Arc<Descriptor>,
network: Network,
persister: Arc<Persister>,
lookahead: u32,
) -> Result<Self, CreateWithPersistError>
pub fn create_single( descriptor: Arc<Descriptor>, network: Network, persister: Arc<Persister>, lookahead: u32, ) -> Result<Self, CreateWithPersistError>
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.
Sourcepub fn create_from_two_path_descriptor(
two_path_descriptor: Arc<Descriptor>,
network: Network,
persister: Arc<Persister>,
lookahead: u32,
) -> Result<Self, CreateWithPersistError>
pub fn create_from_two_path_descriptor( two_path_descriptor: Arc<Descriptor>, network: Network, persister: Arc<Persister>, lookahead: u32, ) -> Result<Self, CreateWithPersistError>
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 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.
Sourcepub fn load(
descriptor: Arc<Descriptor>,
change_descriptor: Arc<Descriptor>,
persister: Arc<Persister>,
lookahead: u32,
) -> Result<Wallet, LoadWithPersistError>
pub fn load( descriptor: Arc<Descriptor>, change_descriptor: Arc<Descriptor>, persister: Arc<Persister>, lookahead: u32, ) -> Result<Wallet, LoadWithPersistError>
Build Wallet by loading from persistence.
Note that the descriptor secret keys are not persisted to the db.
Sourcepub fn load_single(
descriptor: Arc<Descriptor>,
persister: Arc<Persister>,
lookahead: u32,
) -> Result<Wallet, LoadWithPersistError>
pub fn load_single( descriptor: Arc<Descriptor>, persister: Arc<Persister>, lookahead: u32, ) -> Result<Wallet, LoadWithPersistError>
Build a single-descriptor Wallet by loading from persistence.
Note that the descriptor secret keys are not persisted to the db.
Sourcepub fn derivation_of_spk(&self, spk: Arc<Script>) -> Option<KeychainAndIndex>
pub fn derivation_of_spk(&self, spk: Arc<Script>) -> Option<KeychainAndIndex>
Finds how the wallet derived the script pubkey spk.
Will only return Some(_) if the wallet has given out the spk.
Sourcepub fn cancel_tx(&self, tx: &Transaction)
pub fn cancel_tx(&self, tx: &Transaction)
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.
Sourcepub fn get_utxo(&self, op: OutPoint) -> Option<LocalOutput>
pub fn get_utxo(&self, op: OutPoint) -> Option<LocalOutput>
Returns the utxo owned by this wallet corresponding to outpoint if it exists in the
wallet’s database.
Sourcepub fn reveal_next_address(&self, keychain: KeychainKind) -> AddressInfo
pub fn reveal_next_address(&self, keychain: KeychainKind) -> AddressInfo
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, then the last revealed address will be returned.
Sourcepub fn peek_address(&self, keychain: KeychainKind, index: u32) -> AddressInfo
pub fn peek_address(&self, keychain: KeychainKind, index: u32) -> AddressInfo
Sourcepub fn next_derivation_index(&self, keychain: KeychainKind) -> u32
pub fn next_derivation_index(&self, keychain: KeychainKind) -> u32
The index of the next address that you would get if you were to ask the wallet for a new address.
Sourcepub fn next_unused_address(&self, keychain: KeychainKind) -> AddressInfo
pub fn next_unused_address(&self, keychain: KeychainKind) -> AddressInfo
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.
Sourcepub fn mark_used(&self, keychain: KeychainKind, index: u32) -> bool
pub fn mark_used(&self, keychain: KeychainKind, index: u32) -> bool
Marks an address used of the given keychain at index.
Returns whether the given index was present and then removed from the unused set.
Sourcepub fn unmark_used(&self, keychain: KeychainKind, index: u32) -> bool
pub fn unmark_used(&self, keychain: KeychainKind, index: u32) -> bool
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.
Sourcepub fn reveal_addresses_to(
&self,
keychain: KeychainKind,
index: u32,
) -> Vec<AddressInfo>
pub fn reveal_addresses_to( &self, keychain: KeychainKind, index: u32, ) -> Vec<AddressInfo>
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.
Sourcepub fn list_unused_addresses(&self, keychain: KeychainKind) -> Vec<AddressInfo>
pub fn list_unused_addresses(&self, keychain: KeychainKind) -> Vec<AddressInfo>
List addresses that are revealed but unused.
Note if the returned iterator is empty you can reveal more addresses
by using reveal_next_address or
reveal_addresses_to.
Sourcepub fn apply_update(
&self,
update: Arc<Update>,
) -> Result<(), CannotConnectError>
pub fn apply_update( &self, update: Arc<Update>, ) -> Result<(), CannotConnectError>
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.
Sourcepub fn apply_update_events(
&self,
update: Arc<Update>,
) -> Result<Vec<WalletEvent>, CannotConnectError>
pub fn apply_update_events( &self, update: Arc<Update>, ) -> Result<Vec<WalletEvent>, CannotConnectError>
Applies an update to the wallet, stages the changes, and returns events.
Usually you create an update by interacting with some blockchain data source and inserting
transactions related to your wallet into it. Staged changes are NOT persisted.
After applying updates you should process the events in your app before persisting the
staged wallet changes. For an example of how to persist staged wallet changes see
Wallet::reveal_next_address.
Sourcepub fn apply_unconfirmed_txs(&self, unconfirmed_txs: Vec<UnconfirmedTx>)
pub fn apply_unconfirmed_txs(&self, unconfirmed_txs: Vec<UnconfirmedTx>)
Apply relevant unconfirmed transactions to the wallet. Transactions that are not relevant are filtered out.
Sourcepub fn apply_evicted_txs(&self, evicted_txs: Vec<EvictedTx>)
pub fn apply_evicted_txs(&self, evicted_txs: Vec<EvictedTx>)
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
Sourcepub fn derivation_index(&self, keychain: KeychainKind) -> Option<u32>
pub fn derivation_index(&self, keychain: KeychainKind) -> Option<u32>
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.
Sourcepub fn descriptor_checksum(&self, keychain: KeychainKind) -> String
pub fn descriptor_checksum(&self, keychain: KeychainKind) -> String
Return the checksum of the public descriptor associated to keychain.
Internally calls Self::public_descriptor to fetch the right descriptor.
Sourcepub fn policies(
&self,
keychain: KeychainKind,
) -> Result<Option<Arc<Policy>>, DescriptorError>
pub fn policies( &self, keychain: KeychainKind, ) -> Result<Option<Arc<Policy>>, DescriptorError>
Return the spending policies for the wallet’s descriptor.
Sourcepub fn balance(&self) -> Balance
pub fn balance(&self) -> Balance
Return the balance, separated into available, trusted-pending, untrusted-pending and immature values.
Sourcepub fn is_mine(&self, script: Arc<Script>) -> bool
pub fn is_mine(&self, script: Arc<Script>) -> bool
Return whether or not a script is part of this wallet (either internal or external).
Sourcepub fn sign(
&self,
psbt: Arc<Psbt>,
sign_options: Option<SignOptions>,
) -> Result<bool, SignerError>
pub fn sign( &self, psbt: Arc<Psbt>, sign_options: Option<SignOptions>, ) -> Result<bool, SignerError>
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.
Sourcepub fn finalize_psbt(
&self,
psbt: Arc<Psbt>,
sign_options: Option<SignOptions>,
) -> Result<bool, SignerError>
pub fn finalize_psbt( &self, psbt: Arc<Psbt>, sign_options: Option<SignOptions>, ) -> Result<bool, SignerError>
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,
and BIP371
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.
Sourcepub fn sent_and_received(&self, tx: &Transaction) -> SentAndReceivedValues
pub fn sent_and_received(&self, tx: &Transaction) -> SentAndReceivedValues
Compute the tx’s sent and received Amounts.
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.
Sourcepub fn transactions(&self) -> Vec<CanonicalTx>
pub fn transactions(&self) -> Vec<CanonicalTx>
Iterate over the transactions in the wallet.
Sourcepub fn get_tx(
&self,
txid: Arc<Txid>,
) -> Result<Option<CanonicalTx>, TxidParseError>
pub fn get_tx( &self, txid: Arc<Txid>, ) -> Result<Option<CanonicalTx>, TxidParseError>
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.
Sourcepub fn insert_txout(&self, outpoint: OutPoint, txout: TxOut)
pub fn insert_txout(&self, outpoint: OutPoint, txout: TxOut)
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 TxOuts that the wallet does not own. Only
insert TxOuts 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.
Sourcepub fn calculate_fee(
&self,
tx: &Transaction,
) -> Result<Arc<Amount>, CalculateFeeError>
pub fn calculate_fee( &self, tx: &Transaction, ) -> Result<Arc<Amount>, CalculateFeeError>
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.
Sourcepub fn calculate_fee_rate(
&self,
tx: &Transaction,
) -> Result<Arc<FeeRate>, CalculateFeeError>
pub fn calculate_fee_rate( &self, tx: &Transaction, ) -> Result<Arc<FeeRate>, CalculateFeeError>
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.
Sourcepub fn list_unspent(&self) -> Vec<LocalOutput>
pub fn list_unspent(&self) -> Vec<LocalOutput>
Return the list of unspent outputs of this wallet.
Sourcepub fn list_output(&self) -> Vec<LocalOutput>
pub fn list_output(&self) -> Vec<LocalOutput>
List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).
To list only unspent outputs (UTXOs), use Wallet::list_unspent instead.
Sourcepub fn start_full_scan(&self) -> Arc<FullScanRequestBuilder>
pub fn start_full_scan(&self) -> Arc<FullScanRequestBuilder>
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.
Sourcepub fn start_sync_with_revealed_spks(&self) -> Arc<SyncRequestBuilder>
pub fn start_sync_with_revealed_spks(&self) -> Arc<SyncRequestBuilder>
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.
Sourcepub fn persist(
&self,
persister: Arc<Persister>,
) -> Result<bool, PersistenceError>
pub fn persist( &self, persister: Arc<Persister>, ) -> Result<bool, PersistenceError>
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.
Sourcepub fn staged(&self) -> Option<Arc<ChangeSet>>
pub fn staged(&self) -> Option<Arc<ChangeSet>>
Get a reference of the staged ChangeSet that is yet to be committed (if any).
Sourcepub fn take_staged(&self) -> Option<Arc<ChangeSet>>
pub fn take_staged(&self) -> Option<Arc<ChangeSet>>
Take the staged ChangeSet to be persisted now (if any).
Sourcepub fn latest_checkpoint(&self) -> BlockId
pub fn latest_checkpoint(&self) -> BlockId
Returns the latest checkpoint.
Sourcepub fn tx_details(&self, txid: Arc<Txid>) -> Option<TxDetails>
pub fn tx_details(&self, txid: Arc<Txid>) -> Option<TxDetails>
Get the [TxDetails] of a wallet transaction.
Sourcepub fn public_descriptor(&self, keychain: KeychainKind) -> String
pub fn public_descriptor(&self, keychain: KeychainKind) -> String
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.
Trait Implementations§
Source§impl<UT> LowerError<UT> for Wallet
impl<UT> LowerError<UT> for Wallet
Source§fn lower_error(obj: Self) -> RustBuffer
fn lower_error(obj: Self) -> RustBuffer
Source§impl<UT> LowerReturn<UT> for Wallet
impl<UT> LowerReturn<UT> for Wallet
Source§type ReturnType = <Arc<Wallet> as LowerReturn<UniFfiTag>>::ReturnType
type ReturnType = <Arc<Wallet> as LowerReturn<UniFfiTag>>::ReturnType
Source§fn lower_return(obj: Self) -> Result<Self::ReturnType, RustCallError>
fn lower_return(obj: Self) -> Result<Self::ReturnType, RustCallError>
§fn handle_failed_lift(
error: LiftArgsError,
) -> Result<Self::ReturnType, RustCallError>
fn handle_failed_lift( error: LiftArgsError, ) -> Result<Self::ReturnType, RustCallError>
Auto Trait Implementations§
impl !Freeze for Wallet
impl RefUnwindSafe for Wallet
impl Send for Wallet
impl Sync for Wallet
impl Unpin for Wallet
impl UnwindSafe for Wallet
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T, UT> HandleAlloc<UT> for T
impl<T, UT> HandleAlloc<UT> for T
§fn new_handle(value: Arc<T>) -> Handle
fn new_handle(value: Arc<T>) -> Handle
§unsafe fn clone_handle(handle: Handle) -> Handle
unsafe fn clone_handle(handle: Handle) -> Handle
§unsafe fn consume_handle(handle: Handle) -> Arc<T>
unsafe fn consume_handle(handle: Handle) -> Arc<T>
Arc<> Read more