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:
- 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.
source§impl<D> Wallet<D>
impl<D> Wallet<D>
sourcepub fn new<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: D,
network: Network
) -> Result<Self, NewError<D::LoadError>>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
pub fn new<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
db: D,
network: Network
) -> Result<Self, NewError<D::LoadError>>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
Create a wallet from a descriptor
(and an optional change_descriptor
) and load related
transaction data from db
.
sourcepub fn keychains(&self) -> &BTreeMap<KeychainKind, ExtendedDescriptor>
pub fn keychains(&self) -> &BTreeMap<KeychainKind, ExtendedDescriptor>
Iterator over all keychains in this wallet
sourcepub fn get_address(&mut self, address_index: AddressIndex) -> AddressInfowhere
D: PersistBackend<KeychainKind, ConfirmationTime>,
pub fn get_address(&mut self, address_index: AddressIndex) -> AddressInfowhere
D: PersistBackend<KeychainKind, ConfirmationTime>,
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
.
sourcepub fn get_internal_address(
&mut self,
address_index: AddressIndex
) -> AddressInfowhere
D: PersistBackend<KeychainKind, ConfirmationTime>,
pub fn get_internal_address(
&mut self,
address_index: AddressIndex
) -> AddressInfowhere
D: PersistBackend<KeychainKind, ConfirmationTime>,
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
.
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) -> Vec<LocalUtxo>
pub fn list_unspent(&self) -> Vec<LocalUtxo>
Return the list of unspent outputs of this wallet
sourcepub fn checkpoints(&self) -> &BTreeMap<u32, BlockHash>
pub fn checkpoints(&self) -> &BTreeMap<u32, BlockHash>
Get all the checkpoints the wallet is currently storing indexed by height.
sourcepub fn latest_checkpoint(&self) -> Option<BlockId>
pub fn latest_checkpoint(&self) -> Option<BlockId>
Returns the latest checkpoint.
sourcepub fn spks_of_all_keychains(
&self
) -> BTreeMap<KeychainKind, impl Iterator<Item = (u32, Script)> + Clone>
pub fn spks_of_all_keychains(
&self
) -> BTreeMap<KeychainKind, impl Iterator<Item = (u32, Script)> + Clone>
Returns a iterators of all the script pubkeys for the Internal
and Externalvariants in
KeychainKind`.
This is inteded 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 grap.
Note carefully that iterators go over all script pubkeys on the keychains (not what script pubkeys the wallet is storing internally).
sourcepub fn spks_of_keychain(
&self,
keychain: KeychainKind
) -> impl Iterator<Item = (u32, Script)> + Clone
pub fn spks_of_keychain(
&self,
keychain: KeychainKind
) -> impl Iterator<Item = (u32, Script)> + Clone
Gets an iterator over all the script pubkeys in a single keychain.
See spks_of_all_keychains
for more documentation
sourcepub fn get_utxo(&self, op: OutPoint) -> Option<LocalUtxo>
pub fn get_utxo(&self, op: OutPoint) -> Option<LocalUtxo>
Returns the utxo owned by this wallet corresponding to outpoint
if it exists in the
wallet’s database.
sourcepub fn get_tx(&self, txid: Txid, include_raw: bool) -> Option<TransactionDetails>
pub fn get_tx(&self, txid: Txid, include_raw: bool) -> Option<TransactionDetails>
Return a single transactions made and received by the wallet
Optionally fill the TransactionDetails::transaction
field with the raw transaction if
include_raw
is true
.
sourcepub fn insert_checkpoint(
&mut self,
block_id: BlockId
) -> Result<bool, InsertCheckpointError>
pub fn insert_checkpoint(
&mut self,
block_id: BlockId
) -> Result<bool, InsertCheckpointError>
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<ConfirmationTime>>
pub fn insert_tx(
&mut self,
tx: Transaction,
position: ConfirmationTime
) -> Result<bool, InsertTxError<ConfirmationTime>>
Add a transaction to the wallet’s internal view of the chain.
This stages but does not commit
the change.
There are a number reasons tx
could be rejected with an Err(_)
. The most important one
is that the transaction is at a height that is greater than latest_checkpoint
. Therefore
you should use insert_checkpoint
to insert new checkpoints before manually inserting new
transactions.
Returns whether anything changed with the transaction insertion (e.g. false
if the
transaction was already inserted at the same position).
sourcepub fn list_transactions(&self, include_raw: bool) -> Vec<TransactionDetails>
👎Deprecated: use Wallet::transactions instead
pub fn list_transactions(&self, include_raw: bool) -> Vec<TransactionDetails>
Deprecated. use Wallet::transactions
instead.
sourcepub fn transactions(
&self
) -> impl DoubleEndedIterator<Item = (ConfirmationTime, &Transaction)> + '_
pub fn transactions(
&self
) -> impl DoubleEndedIterator<Item = (ConfirmationTime, &Transaction)> + '_
Iterate over the transactions in the wallet in order of ascending confirmation time with unconfirmed transactions last.
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<'_, D, DefaultCoinSelectionAlgorithm, CreateTx>
pub fn build_tx(
&mut self
) -> TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, CreateTx>
sourcepub fn build_fee_bump(
&mut self,
txid: Txid
) -> Result<TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, BumpFee>, Error>
pub fn build_fee_bump(
&mut self,
txid: Txid
) -> Result<TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, BumpFee>, Error>
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(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
sourcepub fn sign(
&self,
psbt: &mut PartiallySignedTransaction,
sign_options: SignOptions
) -> Result<bool, Error>
pub fn sign(
&self,
psbt: &mut PartiallySignedTransaction,
sign_options: SignOptions
) -> Result<bool, Error>
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");
sourcepub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, Error>
pub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, Error>
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 PartiallySignedTransaction,
sign_options: SignOptions
) -> Result<bool, Error>
pub fn finalize_psbt(
&self,
psbt: &mut PartiallySignedTransaction,
sign_options: SignOptions
) -> Result<bool, Error>
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: LocalUtxo,
sighash_type: Option<PsbtSighashType>,
only_witness_utxo: bool
) -> Result<Input, Error>
pub fn get_psbt_input(
&self,
utxo: LocalUtxo,
sighash_type: Option<PsbtSighashType>,
only_witness_utxo: bool
) -> Result<Input, Error>
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: Update) -> Result<(), UpdateError>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
pub fn apply_update(&mut self, update: Update) -> Result<(), UpdateError>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
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<(), D::WriteError>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
pub fn commit(&mut self) -> Result<(), D::WriteError>where
D: PersistBackend<KeychainKind, ConfirmationTime>,
Commits all curently staged
changed to the persistence backend returning and error when this fails.
sourcepub fn staged(&self) -> &KeychainChangeSet<KeychainKind, ConfirmationTime>
pub fn staged(&self) -> &KeychainChangeSet<KeychainKind, ConfirmationTime>
Returns the changes that will be staged with the next call to commit
.
sourcepub fn as_chain_graph(&self) -> &ChainGraph<ConfirmationTime>
pub fn as_chain_graph(&self) -> &ChainGraph<ConfirmationTime>
Get a reference to the inner ChainGraph
.