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:
Implementations
sourceimpl<D> Wallet<D> where
D: BatchDatabase,
impl<D> Wallet<D> where
D: BatchDatabase,
sourcepub fn new_offline<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network,
database: D
) -> Result<Self, Error>
👎 Deprecated: Just use Wallet::new – all wallets are offline now!
pub fn new_offline<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network,
database: D
) -> Result<Self, Error>
Just use Wallet::new – all wallets are offline now!
Create a new “offline” wallet
sourcepub fn new<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network,
database: D
) -> Result<Self, Error>
pub fn new<E: IntoWalletDescriptor>(
descriptor: E,
change_descriptor: Option<E>,
network: Network,
database: D
) -> Result<Self, Error>
Create a wallet.
The only way this can fail is if the descriptors passed in do not match the checksums in database
.
sourcepub fn get_address(
&self,
address_index: AddressIndex
) -> Result<AddressInfo, Error>
pub fn get_address(
&self,
address_index: AddressIndex
) -> Result<AddressInfo, Error>
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(
&self,
address_index: AddressIndex
) -> Result<AddressInfo, Error>
pub fn get_internal_address(
&self,
address_index: AddressIndex
) -> Result<AddressInfo, Error>
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 ensure_addresses_cached(&self, max_addresses: u32) -> Result<bool, Error>
pub fn ensure_addresses_cached(&self, max_addresses: u32) -> Result<bool, Error>
Ensures that there are at least max_addresses
addresses cached in the database if the
descriptor is derivable, or 1 address if it is not.
Will return Ok(true)
if there are new addresses generated (either external or internal),
and Ok(false)
if all the required addresses are already cached. This function is useful to
explicitly cache addresses in a wallet to do things like check Wallet::is_mine
on
transaction output scripts.
sourcepub fn is_mine(&self, script: &Script) -> Result<bool, Error>
pub fn is_mine(&self, script: &Script) -> Result<bool, Error>
Return whether or not a script
is part of this wallet (either internal or external)
sourcepub fn list_unspent(&self) -> Result<Vec<LocalUtxo>, Error>
pub fn list_unspent(&self) -> Result<Vec<LocalUtxo>, Error>
Return the list of unspent outputs of this wallet
Note that this method only operates on the internal database, which first needs to be
Wallet::sync
manually.
sourcepub fn get_utxo(&self, outpoint: OutPoint) -> Result<Option<LocalUtxo>, Error>
pub fn get_utxo(&self, outpoint: OutPoint) -> Result<Option<LocalUtxo>, Error>
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
) -> Result<Option<TransactionDetails>, Error>
pub fn get_tx(
&self,
txid: &Txid,
include_raw: bool
) -> Result<Option<TransactionDetails>, Error>
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
.
Note that this method only operates on the internal database, which first needs to be
Wallet::sync
manually.
sourcepub fn list_transactions(
&self,
include_raw: bool
) -> Result<Vec<TransactionDetails>, Error>
pub fn list_transactions(
&self,
include_raw: bool
) -> Result<Vec<TransactionDetails>, Error>
Return an unsorted list of transactions made and received by the wallet
Optionally fill the TransactionDetails::transaction
field with the raw transaction if
include_raw
is true
.
To sort transactions, the following code can be used:
tx_list.sort_by(|a, b| {
b.confirmation_time
.as_ref()
.map(|t| t.height)
.cmp(&a.confirmation_time.as_ref().map(|t| t.height))
});
Note that this method only operates on the internal database, which first needs to be
Wallet::sync
manually.
sourcepub fn get_balance(&self) -> Result<Balance, Error>
pub fn get_balance(&self) -> Result<Balance, Error>
Return the balance, separated into available, trusted-pending, untrusted-pending and immature values.
Note that this method only operates on the internal database, which first needs to be
Wallet::sync
manually.
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("wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/0'/0'/0/*)", None, Network::Testnet, MemoryDatabase::new())?;
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 add_address_validator(&mut self, validator: Arc<dyn AddressValidator>)
👎 Deprecated
pub fn add_address_validator(&mut self, validator: Arc<dyn AddressValidator>)
Add an address validator
See the address_validator
module for an example.
sourcepub fn get_address_validators(&self) -> &[Arc<dyn AddressValidator>]
👎 Deprecated
pub fn get_address_validators(&self) -> &[Arc<dyn AddressValidator>]
Get the address validators
sourcepub fn build_tx(
&self
) -> TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, CreateTx>
pub fn build_tx(
&self
) -> TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, CreateTx>
sourcepub fn build_fee_bump(
&self,
txid: Txid
) -> Result<TxBuilder<'_, D, DefaultCoinSelectionAlgorithm, BumpFee>, Error>
pub fn build_fee_bump(
&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
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
) -> Result<Option<ExtendedDescriptor>, Error>
pub fn public_descriptor(
&self,
keychain: KeychainKind
) -> Result<Option<ExtendedDescriptor>, Error>
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>
Try to finalize a PSBT
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 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 database(&self) -> impl Deref<Target = D> + '_
pub fn database(&self) -> impl Deref<Target = D> + '_
Return an immutable reference to the internal database
sourcepub fn sync<B: WalletSync + GetHeight>(
&self,
blockchain: &B,
sync_opts: SyncOptions
) -> Result<(), Error>
pub fn sync<B: WalletSync + GetHeight>(
&self,
blockchain: &B,
sync_opts: SyncOptions
) -> Result<(), Error>
Sync the internal database with the blockchain
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
Trait Implementations
Auto Trait Implementations
impl<D> !RefUnwindSafe for Wallet<D>
impl<D> Send for Wallet<D> where
D: Send,
impl<D> !Sync for Wallet<D>
impl<D> Unpin for Wallet<D> where
D: Unpin,
impl<D> !UnwindSafe for Wallet<D>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more