bdkffi::wallet

Struct Wallet

Source
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:

  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.

Implementations§

Source§

impl Wallet

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn peek_address(&self, keychain: KeychainKind, index: u32) -> AddressInfo

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source

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.

Source

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.

Source

pub fn policies( &self, keychain: KeychainKind, ) -> Result<Option<Arc<Policy>>, DescriptorError>

Return the spending policies for the wallet’s descriptor.

Source

pub fn network(&self) -> Network

Get the Bitcoin network the wallet is using.

Source

pub fn balance(&self) -> Balance

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

Source

pub fn is_mine(&self, script: Arc<Script>) -> bool

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

Source

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.

Source

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.

Source

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.

Source

pub fn transactions(&self) -> Vec<CanonicalTx>

Iterate over the transactions in the wallet.

Source

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

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.

Source

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.

Source

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.

Source

pub fn list_unspent(&self) -> Vec<LocalOutput>

Return the list of unspent outputs of this wallet.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn staged(&self) -> Option<Arc<ChangeSet>>

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

Source

pub fn take_staged(&self) -> Option<Arc<ChangeSet>>

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

Source

pub fn latest_checkpoint(&self) -> BlockId

Returns the latest checkpoint.

Source

pub fn tx_details(&self, txid: Arc<Txid>) -> Option<TxDetails>

Get the [TxDetails] of a wallet transaction.

Source

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> LiftRef<UT> for Wallet

Source§

impl<UT> LowerError<UT> for Wallet

Source§

fn lower_error(obj: Self) -> RustBuffer

Lower this value for scaffolding function return Read more
Source§

impl<UT> LowerReturn<UT> for Wallet

Source§

type ReturnType = <Arc<Wallet> as LowerReturn<UniFfiTag>>::ReturnType

The type that should be returned by scaffolding functions for this type. Read more
Source§

fn lower_return(obj: Self) -> Result<Self::ReturnType, RustCallError>

Lower the return value from an scaffolding call Read more
§

fn handle_failed_lift( error: LiftArgsError, ) -> Result<Self::ReturnType, RustCallError>

Lower the return value for failed argument lifts Read more
Source§

impl<UT> TypeId<UT> for Wallet

Source§

const TYPE_ID_META: MetadataBuffer

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
§

unsafe fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
§

unsafe fn consume_handle(handle: Handle) -> Arc<T>

Consume a handle, getting back the initial Arc<> Read more
§

unsafe fn get_arc(handle: Handle) -> Arc<Self>

Get a clone of the Arc<> using a “borrowed” handle. Read more
Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V