Struct bdk_wallet::wallet::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:
- output descriptors from which it can derive addresses.
signer
s that can contribute signatures to addresses instantiated from the descriptors.
Implementations§
source§impl Wallet
impl Wallet
sourcepub fn new_no_persist<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network
) -> Result<Self, DescriptorError>
pub fn new_no_persist<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, network: Network ) -> Result<Self, DescriptorError>
Creates a wallet that does not persist data.
sourcepub fn new_no_persist_with_genesis_hash<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network,
genesis_hash: BlockHash
) -> Result<Self, DescriptorError>
pub fn new_no_persist_with_genesis_hash<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, network: Network, genesis_hash: BlockHash ) -> Result<Self, DescriptorError>
Creates a wallet that does not persist data, with a custom genesis hash.
source§impl Wallet
impl Wallet
sourcepub fn new<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
network: Network
) -> Result<Self, NewError>
pub fn new<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, db: impl PersistBackend<ChangeSet> + Send + Sync + 'static, network: Network ) -> Result<Self, NewError>
Initialize an empty Wallet
.
sourcepub fn new_with_genesis_hash<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
network: Network,
genesis_hash: BlockHash
) -> Result<Self, NewError>
pub fn new_with_genesis_hash<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, db: impl PersistBackend<ChangeSet> + Send + Sync + 'static, network: Network, genesis_hash: BlockHash ) -> Result<Self, NewError>
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.
sourcepub fn load(
db: impl PersistBackend<ChangeSet> + Send + Sync + 'static
) -> Result<Self, LoadError>
pub fn load( db: impl PersistBackend<ChangeSet> + Send + Sync + 'static ) -> Result<Self, LoadError>
Load Wallet
from the given persistence backend.
Note that the descriptor secret keys are not persisted to the db; this means that after
calling this method the Wallet
won’t know the secret keys, and as such, won’t be
able to sign transactions.
If you wish to use the wallet to sign transactions, you need to add the secret keys
manually to the Wallet
:
let secp = Secp256k1::new();
let (external_descriptor, external_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)").unwrap();
let (internal_descriptor, internal_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)").unwrap();
let external_signer_container = SignersContainer::build(external_keymap, &external_descriptor, &secp);
let internal_signer_container = SignersContainer::build(internal_keymap, &internal_descriptor, &secp);
let mut wallet = Wallet::load(db)?;
external_signer_container.signers().into_iter()
.for_each(|s| wallet.add_signer(KeychainKind::External, SignerOrdering::default(), s.clone()));
internal_signer_container.signers().into_iter()
.for_each(|s| wallet.add_signer(KeychainKind::Internal, SignerOrdering::default(), s.clone()));
Alternatively, you can call Wallet::new_or_load
, which will add the private keys of the
passed-in descriptors to the Wallet
.
sourcepub fn new_or_load<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
network: Network
) -> Result<Self, NewOrLoadError>
pub fn new_or_load<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, db: impl PersistBackend<ChangeSet> + Send + Sync + 'static, network: Network ) -> Result<Self, NewOrLoadError>
sourcepub fn new_or_load_with_genesis_hash<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
network: Network,
genesis_hash: BlockHash
) -> Result<Self, NewOrLoadError>
pub fn new_or_load_with_genesis_hash<E: IntoWalletDescriptor>( descriptor: E, change_descriptor: Option<E>, db: impl PersistBackend<ChangeSet> + Send + Sync + 'static, network: Network, genesis_hash: BlockHash ) -> Result<Self, NewOrLoadError>
Either loads Wallet
from persistence, or initializes it if it does not exist, using the
provided descriptor, change descriptor, network, and 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.
sourcepub fn keychains(
&self
) -> impl Iterator<Item = (&KeychainKind, &ExtendedDescriptor)>
pub fn keychains( &self ) -> impl Iterator<Item = (&KeychainKind, &ExtendedDescriptor)>
Iterator over all keychains in this wallet
sourcepub fn peek_address(&self, keychain: KeychainKind, index: u32) -> AddressInfo
pub fn peek_address(&self, keychain: KeychainKind, index: u32) -> AddressInfo
sourcepub fn reveal_next_address(
&mut self,
keychain: KeychainKind
) -> Result<AddressInfo>
pub fn reveal_next_address( &mut self, keychain: KeychainKind ) -> Result<AddressInfo>
Attempt to reveal the next address of the given keychain
.
This will increment the internal 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 returns the last revealed address.
§Errors
If writing to persistent storage fails.
sourcepub fn reveal_addresses_to(
&mut self,
keychain: KeychainKind,
index: u32
) -> Result<impl Iterator<Item = AddressInfo> + '_>
pub fn reveal_addresses_to( &mut self, keychain: KeychainKind, index: u32 ) -> Result<impl Iterator<Item = 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.
§Errors
If writing to persistent storage fails.
sourcepub fn next_unused_address(
&mut self,
keychain: KeychainKind
) -> Result<AddressInfo>
pub fn next_unused_address( &mut self, keychain: KeychainKind ) -> Result<AddressInfo>
Get the next unused address for the given keychain
, i.e. the address with the lowest
derivation index that hasn’t been used.
This will attempt to derive and reveal a new address if no newly revealed addresses
are available. See also reveal_next_address
.
§Errors
If writing to persistent storage fails.
sourcepub fn mark_used(&mut self, keychain: KeychainKind, index: u32) -> bool
pub fn mark_used(&mut 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(&mut self, keychain: KeychainKind, index: u32) -> bool
pub fn unmark_used(&mut 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 list_unused_addresses(
&self,
keychain: KeychainKind
) -> impl DoubleEndedIterator<Item = AddressInfo> + '_
pub fn list_unused_addresses( &self, keychain: KeychainKind ) -> impl DoubleEndedIterator<Item = 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 is_mine(&self, script: &Script) -> bool
pub fn is_mine(&self, script: &Script) -> bool
Return whether or not a script
is part of this wallet (either internal or external)
sourcepub fn derivation_of_spk(&self, spk: &Script) -> Option<(KeychainKind, u32)>
pub fn derivation_of_spk(&self, spk: &Script) -> Option<(KeychainKind, u32)>
Finds how the wallet derived the script pubkey spk
.
Will only return Some(_)
if the wallet has given out the spk.
sourcepub fn list_unspent(&self) -> impl Iterator<Item = LocalOutput> + '_
pub fn list_unspent(&self) -> impl Iterator<Item = LocalOutput> + '_
Return the list of unspent outputs of this wallet
sourcepub fn list_output(&self) -> impl Iterator<Item = LocalOutput> + '_
pub fn list_output(&self) -> impl Iterator<Item = 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 checkpoints(&self) -> CheckPointIter
pub fn checkpoints(&self) -> CheckPointIter
Get all the checkpoints the wallet is currently storing indexed by height.
sourcepub fn latest_checkpoint(&self) -> CheckPoint
pub fn latest_checkpoint(&self) -> CheckPoint
Returns the latest checkpoint.
sourcepub fn all_unbounded_spk_iters(
&self
) -> BTreeMap<KeychainKind, impl Iterator<Item = (u32, ScriptBuf)> + Clone>
pub fn all_unbounded_spk_iters( &self ) -> BTreeMap<KeychainKind, impl Iterator<Item = (u32, ScriptBuf)> + Clone>
Get unbounded script pubkey iterators for both Internal
and External
keychains.
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).
sourcepub fn unbounded_spk_iter(
&self,
keychain: KeychainKind
) -> impl Iterator<Item = (u32, ScriptBuf)> + Clone
pub fn unbounded_spk_iter( &self, keychain: KeychainKind ) -> impl Iterator<Item = (u32, ScriptBuf)> + Clone
Get an unbounded script pubkey iterator for the given keychain
.
See all_unbounded_spk_iters
for more documentation
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 insert_txout(&mut self, outpoint: OutPoint, txout: TxOut)
pub fn insert_txout(&mut 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
.
Any inserted TxOut
s are not persisted until commit
is called.
WARNING: 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!
sourcepub fn calculate_fee(&self, tx: &Transaction) -> Result<u64, CalculateFeeError>
pub fn calculate_fee(&self, tx: &Transaction) -> Result<u64, CalculateFeeError>
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().expect("tx");
let fee = wallet.calculate_fee(tx).expect("fee");
sourcepub fn calculate_fee_rate(
&self,
tx: &Transaction
) -> Result<FeeRate, CalculateFeeError>
pub fn calculate_fee_rate( &self, tx: &Transaction ) -> Result<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.
§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().expect("tx");
let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
sourcepub fn sent_and_received(&self, tx: &Transaction) -> (Amount, Amount)
pub fn sent_and_received(&self, tx: &Transaction) -> (Amount, Amount)
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.
§Examples
let tx = wallet.get_tx(txid).expect("tx exists").tx_node.tx;
let (sent, received) = wallet.sent_and_received(&tx);
let tx = &psbt.clone().extract_tx().expect("tx");
let (sent, received) = wallet.sent_and_received(tx);
sourcepub fn get_tx(
&self,
txid: Txid
) -> Option<CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>>
pub fn get_tx( &self, txid: Txid ) -> Option<CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>>
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
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.
use bdk_chain::Anchor;
use bdk_wallet::{chain::ChainPosition, Wallet};
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,
),
}
sourcepub fn insert_checkpoint(
&mut self,
block_id: BlockId
) -> Result<bool, AlterCheckPointError>
pub fn insert_checkpoint( &mut self, block_id: BlockId ) -> Result<bool, AlterCheckPointError>
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).
sourcepub fn insert_tx(
&mut self,
tx: Transaction,
position: ConfirmationTime
) -> Result<bool, InsertTxError>
pub fn insert_tx( &mut self, tx: Transaction, position: ConfirmationTime ) -> Result<bool, InsertTxError>
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.
sourcepub fn transactions(
&self
) -> impl Iterator<Item = CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> + '_
pub fn transactions( &self ) -> impl Iterator<Item = CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> + '_
Iterate over the transactions in the wallet.
sourcepub fn get_balance(&self) -> Balance
pub fn get_balance(&self) -> Balance
Return the balance, separated into available, trusted-pending, untrusted-pending and immature values.
sourcepub fn add_signer(
&mut self,
keychain: KeychainKind,
ordering: SignerOrdering,
signer: Arc<dyn TransactionSigner>
)
pub fn add_signer( &mut self, keychain: KeychainKind, ordering: SignerOrdering, signer: Arc<dyn TransactionSigner> )
Add an external signer
See the signer
module for an example.
sourcepub fn get_signers(&self, keychain: KeychainKind) -> Arc<SignersContainer>
pub fn get_signers(&self, keychain: KeychainKind) -> Arc<SignersContainer>
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>>(())
sourcepub fn build_tx(&mut self) -> TxBuilder<'_, DefaultCoinSelectionAlgorithm>
pub fn build_tx(&mut self) -> TxBuilder<'_, DefaultCoinSelectionAlgorithm>
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(), Amount::from_sat(50_000));
builder.finish()?
};
// sign and broadcast ...
sourcepub fn build_fee_bump(
&mut self,
txid: Txid
) -> Result<TxBuilder<'_, DefaultCoinSelectionAlgorithm>, BuildFeeBumpError>
pub fn build_fee_bump( &mut self, txid: Txid ) -> Result<TxBuilder<'_, DefaultCoinSelectionAlgorithm>, BuildFeeBumpError>
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(), Amount::from_sat(50_000))
.enable_rbf();
builder.finish()?
};
let _ = wallet.sign(&mut psbt, SignOptions::default())?;
let tx = psbt.clone().extract_tx().expect("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(FeeRate::from_sat_per_vb(5).expect("valid feerate"));
builder.finish()?
};
let _ = wallet.sign(&mut psbt, SignOptions::default())?;
let fee_bumped_tx = psbt.extract_tx();
// broadcast fee_bumped_tx to replace original
sourcepub fn sign(
&self,
psbt: &mut Psbt,
sign_options: SignOptions
) -> Result<bool, SignerError>
pub fn sign( &self, psbt: &mut Psbt, sign_options: 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.
§Example
let mut psbt = {
let mut builder = wallet.build_tx();
builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
builder.finish()?
};
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized, "we should have signed all the inputs");
sourcepub fn policies(
&self,
keychain: KeychainKind
) -> Result<Option<Policy>, DescriptorError>
pub fn policies( &self, keychain: KeychainKind ) -> Result<Option<Policy>, DescriptorError>
Return the spending policies for the wallet’s descriptor
sourcepub fn public_descriptor(
&self,
keychain: KeychainKind
) -> Option<&ExtendedDescriptor>
pub fn public_descriptor( &self, keychain: KeychainKind ) -> Option<&ExtendedDescriptor>
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
sourcepub fn finalize_psbt(
&self,
psbt: &mut Psbt,
sign_options: SignOptions
) -> Result<bool, SignerError>
pub fn finalize_psbt( &self, psbt: &mut Psbt, sign_options: 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
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 secp_ctx(&self) -> &Secp256k1<All>
pub fn secp_ctx(&self) -> &Secp256k1<All>
Return the secp256k1 context used for all signing operations
sourcepub fn get_descriptor_for_keychain(
&self,
keychain: KeychainKind
) -> &ExtendedDescriptor
pub fn get_descriptor_for_keychain( &self, keychain: KeychainKind ) -> &ExtendedDescriptor
Returns the descriptor used to create addresses for a particular keychain
.
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 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 cancel_tx(&mut self, tx: &Transaction)
pub fn cancel_tx(&mut 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_psbt_input(
&self,
utxo: LocalOutput,
sighash_type: Option<PsbtSighashType>,
only_witness_utxo: bool
) -> Result<Input, CreateTxError>
pub fn get_psbt_input( &self, utxo: LocalOutput, sighash_type: Option<PsbtSighashType>, only_witness_utxo: bool ) -> Result<Input, CreateTxError>
get the corresponding PSBT Input for a LocalUtxo
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::get_descriptor_for_keychain
to fetch the right descriptor
sourcepub fn apply_update(
&mut self,
update: impl Into<Update>
) -> Result<(), CannotConnectError>
pub fn apply_update( &mut self, update: impl Into<Update> ) -> Result<(), CannotConnectError>
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.
sourcepub fn commit(&mut self) -> Result<bool>
pub fn commit(&mut self) -> Result<bool>
Commits all currently staged
changed to the persistence backend returning and error when
this fails.
This returns whether the update
resulted in any changes.
sourcepub fn staged(&self) -> &ChangeSet
pub fn staged(&self) -> &ChangeSet
Returns the changes that will be committed with the next call to commit
.
sourcepub fn tx_graph(&self) -> &TxGraph<ConfirmationTimeHeightAnchor>
pub fn tx_graph(&self) -> &TxGraph<ConfirmationTimeHeightAnchor>
Get a reference to the inner TxGraph
.
sourcepub fn spk_index(&self) -> &KeychainTxOutIndex<KeychainKind>
pub fn spk_index(&self) -> &KeychainTxOutIndex<KeychainKind>
Get a reference to the inner KeychainTxOutIndex
.
sourcepub fn local_chain(&self) -> &LocalChain
pub fn local_chain(&self) -> &LocalChain
Get a reference to the inner LocalChain
.
sourcepub fn apply_block(
&mut self,
block: &Block,
height: u32
) -> Result<(), CannotConnectError>
pub fn apply_block( &mut self, block: &Block, height: u32 ) -> Result<(), CannotConnectError>
Introduces a block
of height
to the wallet, and tries to connect it to the
prev_blockhash
of the block’s header.
This is a convenience method that is equivalent to calling apply_block_connected_to
with prev_blockhash
and height-1
as the connected_to
parameter.
sourcepub fn apply_block_connected_to(
&mut self,
block: &Block,
height: u32,
connected_to: BlockId
) -> Result<(), ApplyHeaderError>
pub fn apply_block_connected_to( &mut self, block: &Block, height: u32, connected_to: BlockId ) -> Result<(), ApplyHeaderError>
Applies relevant transactions from block
of height
to the wallet, and connects the
block to the internal chain.
The connected_to
parameter informs the wallet how this block connects to the internal
LocalChain
. Relevant transactions are filtered from the block
and inserted into the
internal TxGraph
.
sourcepub fn apply_unconfirmed_txs<'t>(
&mut self,
unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>
)
pub fn apply_unconfirmed_txs<'t>( &mut self, unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)> )
Apply relevant unconfirmed transactions to the wallet.
Transactions that are not relevant are filtered out.
This method takes in an iterator of (tx, last_seen)
where last_seen
is the timestamp of
when the transaction was last seen in the mempool. This is used for conflict resolution
when there is conflicting unconfirmed transactions. The transaction with the later
last_seen
is prioritized.
source§impl Wallet
impl Wallet
Methods to construct sync/full-scan requests for spk-based chain sources.
sourcepub fn start_sync_with_revealed_spks(&self) -> SyncRequest
pub fn start_sync_with_revealed_spks(&self) -> SyncRequest
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 start_full_scan(&self) -> FullScanRequest<KeychainKind>
pub fn start_full_scan(&self) -> FullScanRequest<KeychainKind>
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.