• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bitcoindevkit / bdk / 9638796845

24 Jun 2024 02:52AM UTC coverage: 83.122% (+0.1%) from 83.024%
9638796845

Pull #1486

github

web-flow
Merge 95f76e0f3 into 6dab68d35
Pull Request #1486: refact(chain): Use hash of SPK at index 0 as Descriptor unique ID

7 of 9 new or added lines in 2 files covered. (77.78%)

148 existing lines in 3 files now uncovered.

11214 of 13491 relevant lines covered (83.12%)

16554.98 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.03
/crates/wallet/src/wallet/mod.rs
1
// Bitcoin Dev Kit
2
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
3
//
4
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
5
//
6
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
7
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
9
// You may not use this file except in accordance with one or both of these
10
// licenses.
11

12
//! Wallet
13
//!
14
//! This module defines the [`Wallet`].
15
use crate::collections::{BTreeMap, HashMap};
16
use alloc::{
17
    boxed::Box,
18
    string::{String, ToString},
19
    sync::Arc,
20
    vec::Vec,
21
};
22
pub use bdk_chain::keychain::Balance;
23
use bdk_chain::{
24
    indexed_tx_graph,
25
    keychain::KeychainTxOutIndex,
26
    local_chain::{
27
        self, ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain,
28
    },
29
    spk_client::{FullScanRequest, FullScanResult, SyncRequest, SyncResult},
30
    tx_graph::{CanonicalTx, TxGraph},
31
    Append, BlockId, ChainPosition, ConfirmationTime, ConfirmationTimeHeightAnchor, FullTxOut,
32
    Indexed, IndexedTxGraph,
33
};
34
use bitcoin::secp256k1::{All, Secp256k1};
35
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
36
use bitcoin::{
37
    absolute, psbt, Address, Block, FeeRate, Network, OutPoint, Script, ScriptBuf, Sequence,
38
    Transaction, TxOut, Txid, Witness,
39
};
40
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
41
use bitcoin::{constants::genesis_block, Amount};
42
use core::fmt;
43
use core::mem;
44
use core::ops::Deref;
45
use rand_core::RngCore;
46

47
use descriptor::error::Error as DescriptorError;
48
use miniscript::psbt::{PsbtExt, PsbtInputExt, PsbtInputSatisfier};
49

50
use bdk_chain::tx_graph::CalculateFeeError;
51

52
pub mod coin_selection;
53
pub mod export;
54
pub mod signer;
55
pub mod tx_builder;
56
pub(crate) mod utils;
57

58
pub mod error;
59

60
pub use utils::IsDust;
61

62
use coin_selection::DefaultCoinSelectionAlgorithm;
63
use signer::{SignOptions, SignerOrdering, SignersContainer, TransactionSigner};
64
use tx_builder::{FeePolicy, TxBuilder, TxParams};
65
use utils::{check_nsequence_rbf, After, Older, SecpCtx};
66

67
use crate::descriptor::policy::BuildSatisfaction;
68
use crate::descriptor::{
69
    self, calc_checksum, into_wallet_descriptor_checked, DerivedDescriptor, DescriptorMeta,
70
    ExtendedDescriptor, ExtractPolicy, IntoWalletDescriptor, Policy, XKeyUtils,
71
};
72
use crate::psbt::PsbtUtils;
73
use crate::signer::SignerError;
74
use crate::types::*;
75
use crate::wallet::coin_selection::Excess::{Change, NoChange};
76
use crate::wallet::error::{BuildFeeBumpError, CreateTxError, MiniscriptPsbtError};
77

78
use self::coin_selection::Error;
79

80
const COINBASE_MATURITY: u32 = 100;
81

82
/// A Bitcoin wallet
83
///
84
/// The `Wallet` acts as a way of coherently interfacing with output descriptors and related transactions.
85
/// Its main components are:
86
///
87
/// 1. output *descriptors* from which it can derive addresses.
88
/// 2. [`signer`]s that can contribute signatures to addresses instantiated from the descriptors.
89
///
90
/// The user is responsible for loading and writing wallet changes which are represented as
91
/// [`ChangeSet`]s (see [`take_staged`]). Also see individual functions and example for instructions
92
/// on when [`Wallet`] state needs to be persisted.
93
///
94
/// [`signer`]: crate::signer
95
/// [`take_staged`]: Wallet::take_staged
96
#[derive(Debug)]
97
pub struct Wallet {
98
    signers: Arc<SignersContainer>,
99
    change_signers: Arc<SignersContainer>,
100
    chain: LocalChain,
101
    indexed_graph: IndexedTxGraph<ConfirmationTimeHeightAnchor, KeychainTxOutIndex<KeychainKind>>,
102
    stage: ChangeSet,
103
    network: Network,
104
    secp: SecpCtx,
105
}
106

107
/// An update to [`Wallet`].
108
///
109
/// It updates [`bdk_chain::keychain::KeychainTxOutIndex`], [`bdk_chain::TxGraph`] and [`local_chain::LocalChain`] atomically.
110
#[derive(Debug, Clone, Default)]
111
pub struct Update {
112
    /// Contains the last active derivation indices per keychain (`K`), which is used to update the
113
    /// [`KeychainTxOutIndex`].
114
    pub last_active_indices: BTreeMap<KeychainKind, u32>,
115

116
    /// Update for the wallet's internal [`TxGraph`].
117
    pub graph: TxGraph<ConfirmationTimeHeightAnchor>,
118

119
    /// Update for the wallet's internal [`LocalChain`].
120
    ///
121
    /// [`LocalChain`]: local_chain::LocalChain
122
    pub chain: Option<CheckPoint>,
123
}
124

125
impl From<FullScanResult<KeychainKind>> for Update {
UNCOV
126
    fn from(value: FullScanResult<KeychainKind>) -> Self {
×
UNCOV
127
        Self {
×
UNCOV
128
            last_active_indices: value.last_active_indices,
×
129
            graph: value.graph_update,
×
130
            chain: Some(value.chain_update),
×
131
        }
×
132
    }
×
133
}
134

135
impl From<SyncResult> for Update {
UNCOV
136
    fn from(value: SyncResult) -> Self {
×
UNCOV
137
        Self {
×
UNCOV
138
            last_active_indices: BTreeMap::new(),
×
139
            graph: value.graph_update,
×
140
            chain: Some(value.chain_update),
×
141
        }
×
142
    }
×
143
}
144

145
/// The changes made to a wallet by applying an [`Update`].
146
pub type ChangeSet = bdk_chain::CombinedChangeSet<KeychainKind, ConfirmationTimeHeightAnchor>;
147

148
/// A derived address and the index it was found at.
149
/// For convenience this automatically derefs to `Address`
150
#[derive(Debug, PartialEq, Eq)]
151
pub struct AddressInfo {
152
    /// Child index of this address
153
    pub index: u32,
154
    /// Address
155
    pub address: Address,
156
    /// Type of keychain
157
    pub keychain: KeychainKind,
158
}
159

160
impl Deref for AddressInfo {
161
    type Target = Address;
162

163
    fn deref(&self) -> &Self::Target {
880✔
164
        &self.address
880✔
165
    }
880✔
166
}
167

168
impl fmt::Display for AddressInfo {
169
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208✔
170
        write!(f, "{}", self.address)
208✔
171
    }
208✔
172
}
173

174
/// The error type when constructing a fresh [`Wallet`].
175
///
176
/// Methods [`new`] and [`new_with_genesis_hash`] may return this error.
177
///
178
/// [`new`]: Wallet::new
179
/// [`new_with_genesis_hash`]: Wallet::new_with_genesis_hash
180
#[derive(Debug)]
181
pub enum NewError {
182
    /// There was problem with the passed-in descriptor(s).
183
    Descriptor(crate::descriptor::DescriptorError),
184
}
185

186
impl fmt::Display for NewError {
UNCOV
187
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
UNCOV
188
        match self {
×
UNCOV
189
            NewError::Descriptor(e) => e.fmt(f),
×
190
        }
×
191
    }
×
192
}
193

194
#[cfg(feature = "std")]
195
impl std::error::Error for NewError {}
196

197
/// The error type when loading a [`Wallet`] from a [`ChangeSet`].
198
///
199
/// Method [`load_from_changeset`] may return this error.
200
///
201
/// [`load_from_changeset`]: Wallet::load_from_changeset
202
#[derive(Debug)]
203
pub enum LoadError {
204
    /// There was a problem with the passed-in descriptor(s).
205
    Descriptor(crate::descriptor::DescriptorError),
206
    /// Data loaded from persistence is missing network type.
207
    MissingNetwork,
208
    /// Data loaded from persistence is missing genesis hash.
209
    MissingGenesis,
210
    /// Data loaded from persistence is missing descriptor.
211
    MissingDescriptor(KeychainKind),
212
}
213

214
impl fmt::Display for LoadError {
UNCOV
215
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
UNCOV
216
        match self {
×
UNCOV
217
            LoadError::Descriptor(e) => e.fmt(f),
×
218
            LoadError::MissingNetwork => write!(f, "loaded data is missing network type"),
×
219
            LoadError::MissingGenesis => write!(f, "loaded data is missing genesis hash"),
×
220
            LoadError::MissingDescriptor(k) => {
×
221
                write!(f, "loaded data is missing descriptor for keychain {k:?}")
×
222
            }
223
        }
224
    }
×
225
}
226

227
#[cfg(feature = "std")]
228
impl std::error::Error for LoadError {}
229

230
/// Error type for when we try load a [`Wallet`] from persistence and creating it if non-existent.
231
///
232
/// Methods [`new_or_load`] and [`new_or_load_with_genesis_hash`] may return this error.
233
///
234
/// [`new_or_load`]: Wallet::new_or_load
235
/// [`new_or_load_with_genesis_hash`]: Wallet::new_or_load_with_genesis_hash
236
#[derive(Debug)]
237
pub enum NewOrLoadError {
238
    /// There is a problem with the passed-in descriptor.
239
    Descriptor(crate::descriptor::DescriptorError),
240
    /// The loaded genesis hash does not match what was provided.
241
    LoadedGenesisDoesNotMatch {
242
        /// The expected genesis block hash.
243
        expected: BlockHash,
244
        /// The block hash loaded from persistence.
245
        got: Option<BlockHash>,
246
    },
247
    /// The loaded network type does not match what was provided.
248
    LoadedNetworkDoesNotMatch {
249
        /// The expected network type.
250
        expected: Network,
251
        /// The network type loaded from persistence.
252
        got: Option<Network>,
253
    },
254
    /// The loaded desccriptor does not match what was provided.
255
    LoadedDescriptorDoesNotMatch {
256
        /// The descriptor loaded from persistence.
257
        got: Option<ExtendedDescriptor>,
258
        /// The keychain of the descriptor not matching
259
        keychain: KeychainKind,
260
    },
261
}
262

263
impl fmt::Display for NewOrLoadError {
UNCOV
264
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
UNCOV
265
        match self {
×
UNCOV
266
            NewOrLoadError::Descriptor(e) => e.fmt(f),
×
267
            NewOrLoadError::LoadedGenesisDoesNotMatch { expected, got } => {
×
268
                write!(f, "loaded genesis hash is not {}, got {:?}", expected, got)
×
269
            }
270
            NewOrLoadError::LoadedNetworkDoesNotMatch { expected, got } => {
×
271
                write!(f, "loaded network type is not {}, got {:?}", expected, got)
×
272
            }
273
            NewOrLoadError::LoadedDescriptorDoesNotMatch { got, keychain } => {
×
274
                write!(
×
UNCOV
275
                    f,
×
276
                    "loaded descriptor is different from what was provided, got {:?} for keychain {:?}",
×
277
                    got, keychain
×
278
                )
×
279
            }
280
        }
281
    }
×
282
}
283

284
#[cfg(feature = "std")]
285
impl std::error::Error for NewOrLoadError {}
286

287
/// An error that may occur when inserting a transaction into [`Wallet`].
288
#[derive(Debug)]
289
pub enum InsertTxError {
290
    /// The error variant that occurs when the caller attempts to insert a transaction with a
291
    /// confirmation height that is greater than the internal chain tip.
292
    ConfirmationHeightCannotBeGreaterThanTip {
293
        /// The internal chain's tip height.
294
        tip_height: u32,
295
        /// The introduced transaction's confirmation height.
296
        tx_height: u32,
297
    },
298
}
299

300
impl fmt::Display for InsertTxError {
UNCOV
301
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
UNCOV
302
        match self {
×
UNCOV
303
            InsertTxError::ConfirmationHeightCannotBeGreaterThanTip {
×
304
                tip_height,
×
305
                tx_height,
×
306
            } => {
×
307
                write!(f, "cannot insert tx with confirmation height ({}) higher than internal tip height ({})", tx_height, tip_height)
×
308
            }
×
309
        }
×
310
    }
×
311
}
312

313
#[cfg(feature = "std")]
314
impl std::error::Error for InsertTxError {}
315

316
/// An error that may occur when applying a block to [`Wallet`].
317
#[derive(Debug)]
318
pub enum ApplyBlockError {
319
    /// Occurs when the update chain cannot connect with original chain.
320
    CannotConnect(CannotConnectError),
321
    /// Occurs when the `connected_to` hash does not match the hash derived from `block`.
322
    UnexpectedConnectedToHash {
323
        /// Block hash of `connected_to`.
324
        connected_to_hash: BlockHash,
325
        /// Expected block hash of `connected_to`, as derived from `block`.
326
        expected_hash: BlockHash,
327
    },
328
}
329

330
impl fmt::Display for ApplyBlockError {
UNCOV
331
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
UNCOV
332
        match self {
×
UNCOV
333
            ApplyBlockError::CannotConnect(err) => err.fmt(f),
×
334
            ApplyBlockError::UnexpectedConnectedToHash {
335
                expected_hash: block_hash,
×
336
                connected_to_hash: checkpoint_hash,
×
UNCOV
337
            } => write!(
×
338
                f,
×
339
                "`connected_to` hash {} differs from the expected hash {} (which is derived from `block`)",
×
340
                checkpoint_hash, block_hash
×
341
            ),
×
342
        }
343
    }
×
344
}
345

346
#[cfg(feature = "std")]
347
impl std::error::Error for ApplyBlockError {}
348

349
impl Wallet {
350
    /// Initialize an empty [`Wallet`].
351
    pub fn new<E: IntoWalletDescriptor>(
150✔
352
        descriptor: E,
150✔
353
        change_descriptor: E,
150✔
354
        network: Network,
150✔
355
    ) -> Result<Self, NewError> {
150✔
356
        let genesis_hash = genesis_block(network).block_hash();
150✔
357
        Self::new_with_genesis_hash(descriptor, change_descriptor, network, genesis_hash)
150✔
358
    }
150✔
359

360
    /// Initialize an empty [`Wallet`] with a custom genesis hash.
361
    ///
362
    /// This is like [`Wallet::new`] with an additional `genesis_hash` parameter. This is useful
363
    /// for syncing from alternative networks.
364
    pub fn new_with_genesis_hash<E: IntoWalletDescriptor>(
152✔
365
        descriptor: E,
152✔
366
        change_descriptor: E,
152✔
367
        network: Network,
152✔
368
        genesis_hash: BlockHash,
152✔
369
    ) -> Result<Self, NewError> {
152✔
370
        let secp = Secp256k1::new();
152✔
371
        let (chain, chain_changeset) = LocalChain::from_genesis_hash(genesis_hash);
152✔
372
        let mut index = KeychainTxOutIndex::<KeychainKind>::default();
152✔
373

374
        let (signers, change_signers) =
150✔
375
            create_signers(&mut index, &secp, descriptor, change_descriptor, network)
152✔
376
                .map_err(NewError::Descriptor)?;
152✔
377

378
        let indexed_graph = IndexedTxGraph::new(index);
150✔
379

150✔
380
        let staged = ChangeSet {
150✔
381
            chain: chain_changeset,
150✔
382
            indexed_tx_graph: indexed_graph.initial_changeset(),
150✔
383
            network: Some(network),
150✔
384
        };
150✔
385

150✔
386
        Ok(Wallet {
150✔
387
            signers,
150✔
388
            change_signers,
150✔
389
            network,
150✔
390
            chain,
150✔
391
            indexed_graph,
150✔
392
            stage: staged,
150✔
393
            secp,
150✔
394
        })
150✔
395
    }
152✔
396

397
    /// Load [`Wallet`] from the given previously persisted [`ChangeSet`].
398
    ///
399
    /// Note that the descriptor secret keys are not persisted to the db; this means that after
400
    /// calling this method the [`Wallet`] **won't** know the secret keys, and as such, won't be
401
    /// able to sign transactions.
402
    ///
403
    /// If you wish to use the wallet to sign transactions, you need to add the secret keys
404
    /// manually to the [`Wallet`]:
405
    ///
406
    /// ```rust,no_run
407
    /// # use bdk_wallet::Wallet;
408
    /// # use bdk_wallet::signer::{SignersContainer, SignerOrdering};
409
    /// # use bdk_wallet::descriptor::Descriptor;
410
    /// # use bitcoin::key::Secp256k1;
411
    /// # use bdk_wallet::KeychainKind;
412
    /// use bdk_sqlite::{Store, rusqlite::Connection};
413
    /// #
414
    /// # fn main() -> Result<(), anyhow::Error> {
415
    /// # let temp_dir = tempfile::tempdir().expect("must create tempdir");
416
    /// # let file_path = temp_dir.path().join("store.db");
417
    /// let conn = Connection::open(file_path).expect("must open connection");
418
    /// let mut db = Store::new(conn).expect("must create db");
419
    /// let secp = Secp256k1::new();
420
    ///
421
    /// let (external_descriptor, external_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)").unwrap();
422
    /// let (internal_descriptor, internal_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)").unwrap();
423
    ///
424
    /// let external_signer_container = SignersContainer::build(external_keymap, &external_descriptor, &secp);
425
    /// let internal_signer_container = SignersContainer::build(internal_keymap, &internal_descriptor, &secp);
426
    /// let changeset = db.read()?.expect("there must be an existing changeset");
427
    /// let mut wallet = Wallet::load_from_changeset(changeset)?;
428
    ///
429
    /// external_signer_container.signers().into_iter()
430
    ///     .for_each(|s| wallet.add_signer(KeychainKind::External, SignerOrdering::default(), s.clone()));
431
    /// internal_signer_container.signers().into_iter()
432
    ///     .for_each(|s| wallet.add_signer(KeychainKind::Internal, SignerOrdering::default(), s.clone()));
433
    /// # Ok(())
434
    /// # }
435
    /// ```
436
    ///
437
    /// Alternatively, you can call [`Wallet::new_or_load`], which will add the private keys of the
438
    /// passed-in descriptors to the [`Wallet`].
439
    pub fn load_from_changeset(changeset: ChangeSet) -> Result<Self, LoadError> {
96✔
440
        let secp = Secp256k1::new();
96✔
441
        let network = changeset.network.ok_or(LoadError::MissingNetwork)?;
96✔
442
        let chain =
96✔
443
            LocalChain::from_changeset(changeset.chain).map_err(|_| LoadError::MissingGenesis)?;
96✔
444
        let mut index = KeychainTxOutIndex::<KeychainKind>::default();
96✔
445
        let descriptor = changeset
96✔
446
            .indexed_tx_graph
96✔
447
            .indexer
96✔
448
            .keychains_added
96✔
449
            .get(&KeychainKind::External)
96✔
450
            .ok_or(LoadError::MissingDescriptor(KeychainKind::External))?
96✔
451
            .clone();
96✔
452
        let change_descriptor = changeset
96✔
453
            .indexed_tx_graph
96✔
454
            .indexer
96✔
455
            .keychains_added
96✔
456
            .get(&KeychainKind::Internal)
96✔
457
            .ok_or(LoadError::MissingDescriptor(KeychainKind::Internal))?
96✔
458
            .clone();
96✔
459

96✔
460
        let (signers, change_signers) =
96✔
461
            create_signers(&mut index, &secp, descriptor, change_descriptor, network)
96✔
462
                .expect("Can't fail: we passed in valid descriptors, recovered from the changeset");
96✔
463

96✔
464
        let mut indexed_graph = IndexedTxGraph::new(index);
96✔
465
        indexed_graph.apply_changeset(changeset.indexed_tx_graph);
96✔
466

96✔
467
        let stage = ChangeSet::default();
96✔
468

96✔
469
        Ok(Wallet {
96✔
470
            signers,
96✔
471
            change_signers,
96✔
472
            chain,
96✔
473
            indexed_graph,
96✔
474
            stage,
96✔
475
            network,
96✔
476
            secp,
96✔
477
        })
96✔
478
    }
96✔
479

480
    /// Either loads [`Wallet`] from the given [`ChangeSet`] or initializes it if one does not exist.
481
    ///
482
    /// This method will fail if the loaded [`ChangeSet`] has different parameters to those provided.
483
    ///
484
    /// ```rust,no_run
485
    /// # use bdk_wallet::Wallet;
486
    /// use bdk_sqlite::{Store, rusqlite::Connection};
487
    /// # use bitcoin::Network::Testnet;
488
    /// let conn = Connection::open_in_memory().expect("must open connection");
489
    /// let mut db = Store::new(conn).expect("must create db");
490
    /// let changeset = db.read()?;
491
    ///
492
    /// let external_descriptor = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
493
    /// let internal_descriptor = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
494
    ///
495
    /// let mut wallet = Wallet::new_or_load(external_descriptor, internal_descriptor, changeset, Testnet)?;
496
    /// # Ok::<(), anyhow::Error>(())
497
    /// ```
498
    pub fn new_or_load<E: IntoWalletDescriptor>(
10✔
499
        descriptor: E,
10✔
500
        change_descriptor: E,
10✔
501
        changeset: Option<ChangeSet>,
10✔
502
        network: Network,
10✔
503
    ) -> Result<Self, NewOrLoadError> {
10✔
504
        let genesis_hash = genesis_block(network).block_hash();
10✔
505
        Self::new_or_load_with_genesis_hash(
10✔
506
            descriptor,
10✔
507
            change_descriptor,
10✔
508
            changeset,
10✔
509
            network,
10✔
510
            genesis_hash,
10✔
511
        )
10✔
512
    }
10✔
513

514
    /// Either loads [`Wallet`] from a [`ChangeSet`] or initializes it if one does not exist, using the
515
    /// provided descriptor, change descriptor, network, and custom genesis hash.
516
    ///
517
    /// This method will fail if the loaded [`ChangeSet`] has different parameters to those provided.
518
    /// This is like [`Wallet::new_or_load`] with an additional `genesis_hash` parameter. This is
519
    /// useful for syncing from alternative networks.
520
    pub fn new_or_load_with_genesis_hash<E: IntoWalletDescriptor>(
12✔
521
        descriptor: E,
12✔
522
        change_descriptor: E,
12✔
523
        changeset: Option<ChangeSet>,
12✔
524
        network: Network,
12✔
525
        genesis_hash: BlockHash,
12✔
526
    ) -> Result<Self, NewOrLoadError> {
12✔
527
        if let Some(changeset) = changeset {
12✔
528
            let mut wallet = Self::load_from_changeset(changeset).map_err(|e| match e {
10✔
UNCOV
529
                LoadError::Descriptor(e) => NewOrLoadError::Descriptor(e),
×
UNCOV
530
                LoadError::MissingNetwork => NewOrLoadError::LoadedNetworkDoesNotMatch {
×
UNCOV
531
                    expected: network,
×
532
                    got: None,
×
533
                },
×
534
                LoadError::MissingGenesis => NewOrLoadError::LoadedGenesisDoesNotMatch {
×
535
                    expected: genesis_hash,
×
536
                    got: None,
×
537
                },
×
538
                LoadError::MissingDescriptor(keychain) => {
×
539
                    NewOrLoadError::LoadedDescriptorDoesNotMatch {
×
540
                        got: None,
×
541
                        keychain,
×
542
                    }
×
543
                }
544
            })?;
10✔
545
            if wallet.network != network {
10✔
546
                return Err(NewOrLoadError::LoadedNetworkDoesNotMatch {
2✔
547
                    expected: network,
2✔
548
                    got: Some(wallet.network),
2✔
549
                });
2✔
550
            }
8✔
551
            if wallet.chain.genesis_hash() != genesis_hash {
8✔
552
                return Err(NewOrLoadError::LoadedGenesisDoesNotMatch {
2✔
553
                    expected: genesis_hash,
2✔
554
                    got: Some(wallet.chain.genesis_hash()),
2✔
555
                });
2✔
556
            }
6✔
557

558
            let (expected_descriptor, expected_descriptor_keymap) = descriptor
6✔
559
                .into_wallet_descriptor(&wallet.secp, network)
6✔
560
                .map_err(NewOrLoadError::Descriptor)?;
6✔
561
            let wallet_descriptor = wallet.public_descriptor(KeychainKind::External);
6✔
562
            if wallet_descriptor != &expected_descriptor {
6✔
563
                return Err(NewOrLoadError::LoadedDescriptorDoesNotMatch {
2✔
564
                    got: Some(wallet_descriptor.clone()),
2✔
565
                    keychain: KeychainKind::External,
2✔
566
                });
2✔
567
            }
4✔
568
            // if expected descriptor has private keys add them as new signers
4✔
569
            if !expected_descriptor_keymap.is_empty() {
4✔
570
                let signer_container = SignersContainer::build(
4✔
571
                    expected_descriptor_keymap,
4✔
572
                    &expected_descriptor,
4✔
573
                    &wallet.secp,
4✔
574
                );
4✔
575
                signer_container.signers().into_iter().for_each(|signer| {
4✔
576
                    wallet.add_signer(
4✔
577
                        KeychainKind::External,
4✔
578
                        SignerOrdering::default(),
4✔
579
                        signer.clone(),
4✔
580
                    )
4✔
581
                });
4✔
582
            }
4✔
583

584
            let (expected_change_descriptor, expected_change_descriptor_keymap) = change_descriptor
4✔
585
                .into_wallet_descriptor(&wallet.secp, network)
4✔
586
                .map_err(NewOrLoadError::Descriptor)?;
4✔
587
            let wallet_change_descriptor = wallet.public_descriptor(KeychainKind::Internal);
4✔
588
            if wallet_change_descriptor != &expected_change_descriptor {
4✔
589
                return Err(NewOrLoadError::LoadedDescriptorDoesNotMatch {
2✔
590
                    got: Some(wallet_change_descriptor.clone()),
2✔
591
                    keychain: KeychainKind::Internal,
2✔
592
                });
2✔
593
            }
2✔
594
            // if expected change descriptor has private keys add them as new signers
2✔
595
            if !expected_change_descriptor_keymap.is_empty() {
2✔
596
                let signer_container = SignersContainer::build(
2✔
597
                    expected_change_descriptor_keymap,
2✔
598
                    &expected_change_descriptor,
2✔
599
                    &wallet.secp,
2✔
600
                );
2✔
601
                signer_container.signers().into_iter().for_each(|signer| {
2✔
602
                    wallet.add_signer(
2✔
603
                        KeychainKind::Internal,
2✔
604
                        SignerOrdering::default(),
2✔
605
                        signer.clone(),
2✔
606
                    )
2✔
607
                });
2✔
608
            }
2✔
609

610
            Ok(wallet)
2✔
611
        } else {
612
            Self::new_with_genesis_hash(descriptor, change_descriptor, network, genesis_hash)
2✔
613
                .map_err(|e| match e {
2✔
UNCOV
614
                    NewError::Descriptor(e) => NewOrLoadError::Descriptor(e),
×
615
                })
2✔
616
        }
617
    }
12✔
618

619
    /// Get the Bitcoin network the wallet is using.
620
    pub fn network(&self) -> Network {
48✔
621
        self.network
48✔
622
    }
48✔
623

624
    /// Iterator over all keychains in this wallet
625
    pub fn keychains(&self) -> impl Iterator<Item = (&KeychainKind, &ExtendedDescriptor)> {
64✔
626
        self.indexed_graph.index.keychains()
64✔
627
    }
64✔
628

629
    /// Peek an address of the given `keychain` at `index` without revealing it.
630
    ///
631
    /// For non-wildcard descriptors this returns the same address at every provided index.
632
    ///
633
    /// # Panics
634
    ///
635
    /// This panics when the caller requests for an address of derivation index greater than the
636
    /// [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) max index.
637
    pub fn peek_address(&self, keychain: KeychainKind, mut index: u32) -> AddressInfo {
1,240✔
638
        let mut spk_iter = self
1,240✔
639
            .indexed_graph
1,240✔
640
            .index
1,240✔
641
            .unbounded_spk_iter(&keychain)
1,240✔
642
            .expect("keychain must exist");
1,240✔
643
        if !spk_iter.descriptor().has_wildcard() {
1,240✔
644
            index = 0;
936✔
645
        }
936✔
646
        let (index, spk) = spk_iter
1,240✔
647
            .nth(index as usize)
1,240✔
648
            .expect("derivation index is out of bounds");
1,240✔
649

1,240✔
650
        AddressInfo {
1,240✔
651
            index,
1,240✔
652
            address: Address::from_script(&spk, self.network).expect("must have address form"),
1,240✔
653
            keychain,
1,240✔
654
        }
1,240✔
655
    }
1,240✔
656

657
    /// Attempt to reveal the next address of the given `keychain`.
658
    ///
659
    /// This will increment the keychain's derivation index. If the keychain's descriptor doesn't
660
    /// contain a wildcard or every address is already revealed up to the maximum derivation
661
    /// index defined in [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
662
    /// then the last revealed address will be returned.
663
    ///
664
    /// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
665
    /// calls to this method before closing the wallet. For example:
666
    ///
667
    /// ```rust,no_run
668
    /// # use bdk_wallet::wallet::{Wallet, ChangeSet};
669
    /// # use bdk_wallet::KeychainKind;
670
    /// use bdk_sqlite::{rusqlite::Connection, Store};
671
    /// let conn = Connection::open_in_memory().expect("must open connection");
672
    /// let mut db = Store::new(conn).expect("must create store");
673
    /// # let changeset = ChangeSet::default();
674
    /// # let mut wallet = Wallet::load_from_changeset(changeset).expect("load wallet");
675
    /// let next_address = wallet.reveal_next_address(KeychainKind::External);
676
    /// if let Some(changeset) = wallet.take_staged() {
677
    ///     db.write(&changeset)?;
678
    /// }
679
    ///
680
    /// // Now it's safe to show the user their next address!
681
    /// println!("Next address: {}", next_address.address);
682
    /// # Ok::<(), anyhow::Error>(())
683
    /// ```
684
    pub fn reveal_next_address(&mut self, keychain: KeychainKind) -> AddressInfo {
120✔
685
        let index = &mut self.indexed_graph.index;
120✔
686
        let stage = &mut self.stage;
120✔
687

120✔
688
        let ((index, spk), index_changeset) = index
120✔
689
            .reveal_next_spk(&keychain)
120✔
690
            .expect("keychain must exist");
120✔
691

120✔
692
        stage.append(indexed_tx_graph::ChangeSet::from(index_changeset).into());
120✔
693

120✔
694
        AddressInfo {
120✔
695
            index,
120✔
696
            address: Address::from_script(spk.as_script(), self.network)
120✔
697
                .expect("must have address form"),
120✔
698
            keychain,
120✔
699
        }
120✔
700
    }
120✔
701

702
    /// Reveal addresses up to and including the target `index` and return an iterator
703
    /// of newly revealed addresses.
704
    ///
705
    /// If the target `index` is unreachable, we make a best effort to reveal up to the last
706
    /// possible index. If all addresses up to the given `index` are already revealed, then
707
    /// no new addresses are returned.
708
    ///
709
    /// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
710
    /// calls to this method before closing the wallet. See [`Wallet::reveal_next_address`].
711
    pub fn reveal_addresses_to(
16✔
712
        &mut self,
16✔
713
        keychain: KeychainKind,
16✔
714
        index: u32,
16✔
715
    ) -> impl Iterator<Item = AddressInfo> + '_ {
16✔
716
        let (spks, index_changeset) = self
16✔
717
            .indexed_graph
16✔
718
            .index
16✔
719
            .reveal_to_target(&keychain, index)
16✔
720
            .expect("keychain must exist");
16✔
721

16✔
722
        self.stage.append(index_changeset.into());
16✔
723

16✔
724
        spks.into_iter().map(move |(index, spk)| AddressInfo {
24✔
725
            index,
10✔
726
            address: Address::from_script(&spk, self.network).expect("must have address form"),
10✔
727
            keychain,
10✔
728
        })
24✔
729
    }
16✔
730

731
    /// Get the next unused address for the given `keychain`, i.e. the address with the lowest
732
    /// derivation index that hasn't been used.
733
    ///
734
    /// This will attempt to derive and reveal a new address if no newly revealed addresses
735
    /// are available. See also [`reveal_next_address`](Self::reveal_next_address).
736
    ///
737
    /// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
738
    /// calls to this method before closing the wallet. See [`Wallet::reveal_next_address`].
739
    pub fn next_unused_address(&mut self, keychain: KeychainKind) -> AddressInfo {
888✔
740
        let index = &mut self.indexed_graph.index;
888✔
741

888✔
742
        let ((index, spk), index_changeset) = index
888✔
743
            .next_unused_spk(&keychain)
888✔
744
            .expect("keychain must exist");
888✔
745

888✔
746
        self.stage
888✔
747
            .append(indexed_tx_graph::ChangeSet::from(index_changeset).into());
888✔
748

888✔
749
        AddressInfo {
888✔
750
            index,
888✔
751
            address: Address::from_script(spk.as_script(), self.network)
888✔
752
                .expect("must have address form"),
888✔
753
            keychain,
888✔
754
        }
888✔
755
    }
888✔
756

757
    /// Marks an address used of the given `keychain` at `index`.
758
    ///
759
    /// Returns whether the given index was present and then removed from the unused set.
760
    pub fn mark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
8✔
761
        self.indexed_graph.index.mark_used(keychain, index)
8✔
762
    }
8✔
763

764
    /// Undoes the effect of [`mark_used`] and returns whether the `index` was inserted
765
    /// back into the unused set.
766
    ///
767
    /// Since this is only a superficial marker, it will have no effect if the address at the given
768
    /// `index` was actually used, i.e. the wallet has previously indexed a tx output for the
769
    /// derived spk.
770
    ///
771
    /// [`mark_used`]: Self::mark_used
772
    pub fn unmark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
16✔
773
        self.indexed_graph.index.unmark_used(keychain, index)
16✔
774
    }
16✔
775

776
    /// List addresses that are revealed but unused.
777
    ///
778
    /// Note if the returned iterator is empty you can reveal more addresses
779
    /// by using [`reveal_next_address`](Self::reveal_next_address) or
780
    /// [`reveal_addresses_to`](Self::reveal_addresses_to).
781
    pub fn list_unused_addresses(
24✔
782
        &self,
24✔
783
        keychain: KeychainKind,
24✔
784
    ) -> impl DoubleEndedIterator<Item = AddressInfo> + '_ {
24✔
785
        self.indexed_graph
24✔
786
            .index
24✔
787
            .unused_keychain_spks(&keychain)
24✔
788
            .map(move |(index, spk)| AddressInfo {
32✔
789
                index,
11✔
790
                address: Address::from_script(spk, self.network).expect("must have address form"),
11✔
791
                keychain,
11✔
792
            })
32✔
793
    }
24✔
794

795
    /// Return whether or not a `script` is part of this wallet (either internal or external)
796
    pub fn is_mine(&self, script: &Script) -> bool {
1,760✔
797
        self.indexed_graph.index.index_of_spk(script).is_some()
1,760✔
798
    }
1,760✔
799

800
    /// Finds how the wallet derived the script pubkey `spk`.
801
    ///
802
    /// Will only return `Some(_)` if the wallet has given out the spk.
803
    pub fn derivation_of_spk(&self, spk: &Script) -> Option<(KeychainKind, u32)> {
56✔
804
        self.indexed_graph.index.index_of_spk(spk).cloned()
56✔
805
    }
56✔
806

807
    /// Return the list of unspent outputs of this wallet
808
    pub fn list_unspent(&self) -> impl Iterator<Item = LocalOutput> + '_ {
1,192✔
809
        self.indexed_graph
1,192✔
810
            .graph()
1,192✔
811
            .filter_chain_unspents(
1,192✔
812
                &self.chain,
1,192✔
813
                self.chain.tip().block_id(),
1,192✔
814
                self.indexed_graph.index.outpoints().iter().cloned(),
1,192✔
815
            )
1,192✔
816
            .map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
1,304✔
817
    }
1,192✔
818

819
    /// List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).
820
    ///
821
    /// To list only unspent outputs (UTXOs), use [`Wallet::list_unspent`] instead.
822
    pub fn list_output(&self) -> impl Iterator<Item = LocalOutput> + '_ {
8✔
823
        self.indexed_graph
8✔
824
            .graph()
8✔
825
            .filter_chain_txouts(
8✔
826
                &self.chain,
8✔
827
                self.chain.tip().block_id(),
8✔
828
                self.indexed_graph.index.outpoints().iter().cloned(),
8✔
829
            )
8✔
830
            .map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
9✔
831
    }
8✔
832

833
    /// Get all the checkpoints the wallet is currently storing indexed by height.
UNCOV
834
    pub fn checkpoints(&self) -> CheckPointIter {
×
UNCOV
835
        self.chain.iter_checkpoints()
×
UNCOV
836
    }
×
837

838
    /// Returns the latest checkpoint.
839
    pub fn latest_checkpoint(&self) -> CheckPoint {
72✔
840
        self.chain.tip()
72✔
841
    }
72✔
842

843
    /// Get unbounded script pubkey iterators for both `Internal` and `External` keychains.
844
    ///
845
    /// This is intended to be used when doing a full scan of your addresses (e.g. after restoring
846
    /// from seed words). You pass the `BTreeMap` of iterators to a blockchain data source (e.g.
847
    /// electrum server) which will go through each address until it reaches a *stop gap*.
848
    ///
849
    /// Note carefully that iterators go over **all** script pubkeys on the keychains (not what
850
    /// script pubkeys the wallet is storing internally).
UNCOV
851
    pub fn all_unbounded_spk_iters(
×
UNCOV
852
        &self,
×
UNCOV
853
    ) -> BTreeMap<KeychainKind, impl Iterator<Item = Indexed<ScriptBuf>> + Clone> {
×
854
        self.indexed_graph.index.all_unbounded_spk_iters()
×
855
    }
×
856

857
    /// Get an unbounded script pubkey iterator for the given `keychain`.
858
    ///
859
    /// See [`all_unbounded_spk_iters`] for more documentation
860
    ///
861
    /// [`all_unbounded_spk_iters`]: Self::all_unbounded_spk_iters
UNCOV
862
    pub fn unbounded_spk_iter(
×
UNCOV
863
        &self,
×
UNCOV
864
        keychain: KeychainKind,
×
865
    ) -> impl Iterator<Item = Indexed<ScriptBuf>> + Clone {
×
866
        self.indexed_graph
×
867
            .index
×
868
            .unbounded_spk_iter(&keychain)
×
869
            .expect("keychain must exist")
×
870
    }
×
871

872
    /// Returns the utxo owned by this wallet corresponding to `outpoint` if it exists in the
873
    /// wallet's database.
874
    pub fn get_utxo(&self, op: OutPoint) -> Option<LocalOutput> {
72✔
875
        let ((keychain, index), _) = self.indexed_graph.index.txout(op)?;
72✔
876
        self.indexed_graph
72✔
877
            .graph()
72✔
878
            .filter_chain_unspents(
72✔
879
                &self.chain,
72✔
880
                self.chain.tip().block_id(),
72✔
881
                core::iter::once(((), op)),
72✔
882
            )
72✔
883
            .map(|(_, full_txo)| new_local_utxo(keychain, index, full_txo))
72✔
884
            .next()
72✔
885
    }
72✔
886

887
    /// Inserts a [`TxOut`] at [`OutPoint`] into the wallet's transaction graph.
888
    ///
889
    /// This is used for providing a previous output's value so that we can use [`calculate_fee`]
890
    /// or [`calculate_fee_rate`] on a given transaction. Outputs inserted with this method will
891
    /// not be returned in [`list_unspent`] or [`list_output`].
892
    ///
893
    /// **WARNINGS:** This should only be used to add `TxOut`s that the wallet does not own. Only
894
    /// insert `TxOut`s that you trust the values for!
895
    ///
896
    /// You must persist the changes resulting from one or more calls to this method if you need
897
    /// the inserted `TxOut` data to be reloaded after closing the wallet.
898
    /// See [`Wallet::reveal_next_address`].
899
    ///
900
    /// [`calculate_fee`]: Self::calculate_fee
901
    /// [`calculate_fee_rate`]: Self::calculate_fee_rate
902
    /// [`list_unspent`]: Self::list_unspent
903
    /// [`list_output`]: Self::list_output
904
    pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) {
16✔
905
        let additions = self.indexed_graph.insert_txout(outpoint, txout);
16✔
906
        self.stage.append(additions.into());
16✔
907
    }
16✔
908

909
    /// Calculates the fee of a given transaction. Returns [`Amount::ZERO`] if `tx` is a coinbase transaction.
910
    ///
911
    /// To calculate the fee for a [`Transaction`] with inputs not owned by this wallet you must
912
    /// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
913
    ///
914
    /// Note `tx` does not have to be in the graph for this to work.
915
    ///
916
    /// # Examples
917
    ///
918
    /// ```rust, no_run
919
    /// # use bitcoin::Txid;
920
    /// # use bdk_wallet::Wallet;
921
    /// # let mut wallet: Wallet = todo!();
922
    /// # let txid:Txid = todo!();
923
    /// let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
924
    /// let fee = wallet.calculate_fee(&tx).expect("fee");
925
    /// ```
926
    ///
927
    /// ```rust, no_run
928
    /// # use bitcoin::Psbt;
929
    /// # use bdk_wallet::Wallet;
930
    /// # let mut wallet: Wallet = todo!();
931
    /// # let mut psbt: Psbt = todo!();
932
    /// let tx = &psbt.clone().extract_tx().expect("tx");
933
    /// let fee = wallet.calculate_fee(tx).expect("fee");
934
    /// ```
935
    /// [`insert_txout`]: Self::insert_txout
936
    pub fn calculate_fee(&self, tx: &Transaction) -> Result<Amount, CalculateFeeError> {
536✔
937
        self.indexed_graph.graph().calculate_fee(tx)
536✔
938
    }
536✔
939

940
    /// Calculate the [`FeeRate`] for a given transaction.
941
    ///
942
    /// To calculate the fee rate for a [`Transaction`] with inputs not owned by this wallet you must
943
    /// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
944
    ///
945
    /// Note `tx` does not have to be in the graph for this to work.
946
    ///
947
    /// # Examples
948
    ///
949
    /// ```rust, no_run
950
    /// # use bitcoin::Txid;
951
    /// # use bdk_wallet::Wallet;
952
    /// # let mut wallet: Wallet = todo!();
953
    /// # let txid:Txid = todo!();
954
    /// let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
955
    /// let fee_rate = wallet.calculate_fee_rate(&tx).expect("fee rate");
956
    /// ```
957
    ///
958
    /// ```rust, no_run
959
    /// # use bitcoin::Psbt;
960
    /// # use bdk_wallet::Wallet;
961
    /// # let mut wallet: Wallet = todo!();
962
    /// # let mut psbt: Psbt = todo!();
963
    /// let tx = &psbt.clone().extract_tx().expect("tx");
964
    /// let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
965
    /// ```
966
    /// [`insert_txout`]: Self::insert_txout
967
    pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<FeeRate, CalculateFeeError> {
144✔
968
        self.calculate_fee(tx).map(|fee| fee / tx.weight())
144✔
969
    }
144✔
970

971
    /// Compute the `tx`'s sent and received [`Amount`]s.
972
    ///
973
    /// This method returns a tuple `(sent, received)`. Sent is the sum of the txin amounts
974
    /// that spend from previous txouts tracked by this wallet. Received is the summation
975
    /// of this tx's outputs that send to script pubkeys tracked by this wallet.
976
    ///
977
    /// # Examples
978
    ///
979
    /// ```rust, no_run
980
    /// # use bitcoin::Txid;
981
    /// # use bdk_wallet::Wallet;
982
    /// # let mut wallet: Wallet = todo!();
983
    /// # let txid:Txid = todo!();
984
    /// let tx = wallet.get_tx(txid).expect("tx exists").tx_node.tx;
985
    /// let (sent, received) = wallet.sent_and_received(&tx);
986
    /// ```
987
    ///
988
    /// ```rust, no_run
989
    /// # use bitcoin::Psbt;
990
    /// # use bdk_wallet::Wallet;
991
    /// # let mut wallet: Wallet = todo!();
992
    /// # let mut psbt: Psbt = todo!();
993
    /// let tx = &psbt.clone().extract_tx().expect("tx");
994
    /// let (sent, received) = wallet.sent_and_received(tx);
995
    /// ```
996
    pub fn sent_and_received(&self, tx: &Transaction) -> (Amount, Amount) {
224✔
997
        self.indexed_graph.index.sent_and_received(tx, ..)
224✔
998
    }
224✔
999

1000
    /// Get a single transaction from the wallet as a [`CanonicalTx`] (if the transaction exists).
1001
    ///
1002
    /// `CanonicalTx` contains the full transaction alongside meta-data such as:
1003
    /// * Blocks that the transaction is [`Anchor`]ed in. These may or may not be blocks that exist
1004
    ///   in the best chain.
1005
    /// * The [`ChainPosition`] of the transaction in the best chain - whether the transaction is
1006
    ///   confirmed or unconfirmed. If the transaction is confirmed, the anchor which proves the
1007
    ///   confirmation is provided. If the transaction is unconfirmed, the unix timestamp of when
1008
    ///   the transaction was last seen in the mempool is provided.
1009
    ///
1010
    /// ```rust, no_run
1011
    /// use bdk_chain::Anchor;
1012
    /// use bdk_wallet::{chain::ChainPosition, Wallet};
1013
    /// # let wallet: Wallet = todo!();
1014
    /// # let my_txid: bitcoin::Txid = todo!();
1015
    ///
1016
    /// let canonical_tx = wallet.get_tx(my_txid).expect("panic if tx does not exist");
1017
    ///
1018
    /// // get reference to full transaction
1019
    /// println!("my tx: {:#?}", canonical_tx.tx_node.tx);
1020
    ///
1021
    /// // list all transaction anchors
1022
    /// for anchor in canonical_tx.tx_node.anchors {
1023
    ///     println!(
1024
    ///         "tx is anchored by block of hash {}",
1025
    ///         anchor.anchor_block().hash
1026
    ///     );
1027
    /// }
1028
    ///
1029
    /// // get confirmation status of transaction
1030
    /// match canonical_tx.chain_position {
1031
    ///     ChainPosition::Confirmed(anchor) => println!(
1032
    ///         "tx is confirmed at height {}, we know this since {}:{} is in the best chain",
1033
    ///         anchor.confirmation_height, anchor.anchor_block.height, anchor.anchor_block.hash,
1034
    ///     ),
1035
    ///     ChainPosition::Unconfirmed(last_seen) => println!(
1036
    ///         "tx is last seen at {}, it is unconfirmed as it is not anchored in the best chain",
1037
    ///         last_seen,
1038
    ///     ),
1039
    /// }
1040
    /// ```
1041
    ///
1042
    /// [`Anchor`]: bdk_chain::Anchor
1043
    pub fn get_tx(
56✔
1044
        &self,
56✔
1045
        txid: Txid,
56✔
1046
    ) -> Option<CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> {
56✔
1047
        let graph = self.indexed_graph.graph();
56✔
1048

56✔
1049
        Some(CanonicalTx {
56✔
1050
            chain_position: graph.get_chain_position(
56✔
1051
                &self.chain,
56✔
1052
                self.chain.tip().block_id(),
56✔
1053
                txid,
56✔
1054
            )?,
56✔
1055
            tx_node: graph.get_tx_node(txid)?,
56✔
1056
        })
1057
    }
56✔
1058

1059
    /// Add a new checkpoint to the wallet's internal view of the chain.
1060
    ///
1061
    /// Returns whether anything changed with the insertion (e.g. `false` if checkpoint was already
1062
    /// there).
1063
    ///
1064
    /// **WARNING**: You must persist the changes resulting from one or more calls to this method
1065
    /// if you need the inserted checkpoint data to be reloaded after closing the wallet.
1066
    /// See [`Wallet::reveal_next_address`].
1067
    ///
1068
    /// [`commit`]: Self::commit
1069
    pub fn insert_checkpoint(
2,142✔
1070
        &mut self,
2,142✔
1071
        block_id: BlockId,
2,142✔
1072
    ) -> Result<bool, local_chain::AlterCheckPointError> {
2,142✔
1073
        let changeset = self.chain.insert_block(block_id)?;
2,142✔
1074
        let changed = !changeset.is_empty();
2,142✔
1075
        self.stage.append(changeset.into());
2,142✔
1076
        Ok(changed)
2,142✔
1077
    }
2,142✔
1078

1079
    /// Add a transaction to the wallet's internal view of the chain. This stages the change,
1080
    /// you must persist it later.
1081
    ///
1082
    /// Returns whether anything changed with the transaction insertion (e.g. `false` if the
1083
    /// transaction was already inserted at the same position).
1084
    ///
1085
    /// A `tx` can be rejected if `position` has a height greater than the [`latest_checkpoint`].
1086
    /// Therefore you should use [`insert_checkpoint`] to insert new checkpoints before manually
1087
    /// inserting new transactions.
1088
    ///
1089
    /// **WARNING**: If `position` is confirmed, we anchor the `tx` to the lowest checkpoint that
1090
    /// is >= the `position`'s height. The caller is responsible for ensuring the `tx` exists in our
1091
    /// local view of the best chain's history.
1092
    ///
1093
    /// You must persist the changes resulting from one or more calls to this method if you need
1094
    /// the inserted tx to be reloaded after closing the wallet.
1095
    ///
1096
    /// [`commit`]: Self::commit
1097
    /// [`latest_checkpoint`]: Self::latest_checkpoint
1098
    /// [`insert_checkpoint`]: Self::insert_checkpoint
1099
    pub fn insert_tx(
2,398✔
1100
        &mut self,
2,398✔
1101
        tx: Transaction,
2,398✔
1102
        position: ConfirmationTime,
2,398✔
1103
    ) -> Result<bool, InsertTxError> {
2,398✔
1104
        let (anchor, last_seen) = match position {
2,398✔
1105
            ConfirmationTime::Confirmed { height, time } => {
2,214✔
1106
                // anchor tx to checkpoint with lowest height that is >= position's height
1107
                let anchor = self
2,214✔
1108
                    .chain
2,214✔
1109
                    .range(height..)
2,214✔
1110
                    .last()
2,214✔
1111
                    .ok_or(InsertTxError::ConfirmationHeightCannotBeGreaterThanTip {
2,214✔
1112
                        tip_height: self.chain.tip().height(),
2,214✔
1113
                        tx_height: height,
2,214✔
1114
                    })
2,214✔
1115
                    .map(|anchor_cp| ConfirmationTimeHeightAnchor {
2,214✔
1116
                        anchor_block: anchor_cp.block_id(),
2,214✔
1117
                        confirmation_height: height,
2,214✔
1118
                        confirmation_time: time,
2,214✔
1119
                    })?;
2,214✔
1120

1121
                (Some(anchor), None)
2,214✔
1122
            }
1123
            ConfirmationTime::Unconfirmed { last_seen } => (None, Some(last_seen)),
184✔
1124
        };
1125

1126
        let mut changeset = ChangeSet::default();
2,398✔
1127
        let txid = tx.compute_txid();
2,398✔
1128
        changeset.append(self.indexed_graph.insert_tx(tx).into());
2,398✔
1129
        if let Some(anchor) = anchor {
2,398✔
1130
            changeset.append(self.indexed_graph.insert_anchor(txid, anchor).into());
2,214✔
1131
        }
2,214✔
1132
        if let Some(last_seen) = last_seen {
2,398✔
1133
            changeset.append(self.indexed_graph.insert_seen_at(txid, last_seen).into());
184✔
1134
        }
2,214✔
1135

1136
        let changed = !changeset.is_empty();
2,398✔
1137
        self.stage.append(changeset);
2,398✔
1138
        Ok(changed)
2,398✔
1139
    }
2,398✔
1140

1141
    /// Iterate over the transactions in the wallet.
1142
    pub fn transactions(
38✔
1143
        &self,
38✔
1144
    ) -> impl Iterator<Item = CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> + '_
38✔
1145
    {
38✔
1146
        self.indexed_graph
38✔
1147
            .graph()
38✔
1148
            .list_chain_txs(&self.chain, self.chain.tip().block_id())
38✔
1149
    }
38✔
1150

1151
    /// Return the balance, separated into available, trusted-pending, untrusted-pending and immature
1152
    /// values.
1153
    pub fn balance(&self) -> Balance {
32✔
1154
        self.indexed_graph.graph().balance(
32✔
1155
            &self.chain,
32✔
1156
            self.chain.tip().block_id(),
32✔
1157
            self.indexed_graph.index.outpoints().iter().cloned(),
32✔
1158
            |&(k, _), _| k == KeychainKind::Internal,
32✔
1159
        )
32✔
1160
    }
32✔
1161

1162
    /// Add an external signer
1163
    ///
1164
    /// See [the `signer` module](signer) for an example.
1165
    pub fn add_signer(
64✔
1166
        &mut self,
64✔
1167
        keychain: KeychainKind,
64✔
1168
        ordering: SignerOrdering,
64✔
1169
        signer: Arc<dyn TransactionSigner>,
64✔
1170
    ) {
64✔
1171
        let signers = match keychain {
64✔
1172
            KeychainKind::External => Arc::make_mut(&mut self.signers),
48✔
1173
            KeychainKind::Internal => Arc::make_mut(&mut self.change_signers),
16✔
1174
        };
1175

1176
        signers.add_external(signer.id(&self.secp), ordering, signer);
64✔
1177
    }
64✔
1178

1179
    /// Get the signers
1180
    ///
1181
    /// ## Example
1182
    ///
1183
    /// ```
1184
    /// # use bdk_wallet::{Wallet, KeychainKind};
1185
    /// # use bdk_wallet::bitcoin::Network;
1186
    /// let descriptor = "wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/1'/0'/0/*)";
1187
    /// let change_descriptor = "wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/1'/0'/1/*)";
1188
    /// let wallet = Wallet::new(descriptor, change_descriptor, Network::Testnet)?;
1189
    /// for secret_key in wallet.get_signers(KeychainKind::External).signers().iter().filter_map(|s| s.descriptor_secret_key()) {
1190
    ///     // secret_key: tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/0'/0'/0/*
1191
    ///     println!("secret_key: {}", secret_key);
1192
    /// }
1193
    ///
1194
    /// Ok::<(), Box<dyn std::error::Error>>(())
1195
    /// ```
1196
    pub fn get_signers(&self, keychain: KeychainKind) -> Arc<SignersContainer> {
36✔
1197
        match keychain {
36✔
1198
            KeychainKind::External => Arc::clone(&self.signers),
22✔
1199
            KeychainKind::Internal => Arc::clone(&self.change_signers),
14✔
1200
        }
1201
    }
36✔
1202

1203
    /// Start building a transaction.
1204
    ///
1205
    /// This returns a blank [`TxBuilder`] from which you can specify the parameters for the transaction.
1206
    ///
1207
    /// ## Example
1208
    ///
1209
    /// ```
1210
    /// # use std::str::FromStr;
1211
    /// # use bitcoin::*;
1212
    /// # use bdk_wallet::*;
1213
    /// # use bdk_wallet::wallet::ChangeSet;
1214
    /// # use bdk_wallet::wallet::error::CreateTxError;
1215
    /// # use anyhow::Error;
1216
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1217
    /// # let mut wallet = doctest_wallet!();
1218
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1219
    /// let psbt = {
1220
    ///    let mut builder =  wallet.build_tx();
1221
    ///    builder
1222
    ///        .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
1223
    ///    builder.finish()?
1224
    /// };
1225
    ///
1226
    /// // sign and broadcast ...
1227
    /// # Ok::<(), anyhow::Error>(())
1228
    /// ```
1229
    ///
1230
    /// [`TxBuilder`]: crate::TxBuilder
1231
    pub fn build_tx(&mut self) -> TxBuilder<'_, DefaultCoinSelectionAlgorithm> {
1,088✔
1232
        TxBuilder {
1,088✔
1233
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
1,088✔
1234
            params: TxParams::default(),
1,088✔
1235
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
1,088✔
1236
        }
1,088✔
1237
    }
1,088✔
1238

1239
    pub(crate) fn create_tx<Cs: coin_selection::CoinSelectionAlgorithm>(
145✔
1240
        &mut self,
145✔
1241
        coin_selection: Cs,
145✔
1242
        params: TxParams,
145✔
1243
        rng: &mut impl RngCore,
145✔
1244
    ) -> Result<Psbt, CreateTxError> {
145✔
1245
        let keychains: BTreeMap<_, _> = self.indexed_graph.index.keychains().collect();
145✔
1246
        let external_descriptor = keychains.get(&KeychainKind::External).expect("must exist");
145✔
1247
        let internal_descriptor = keychains.get(&KeychainKind::Internal).expect("must exist");
145✔
1248

1249
        let external_policy = external_descriptor
145✔
1250
            .extract_policy(&self.signers, BuildSatisfaction::None, &self.secp)?
145✔
1251
            .unwrap();
145✔
1252
        let internal_policy = internal_descriptor
145✔
1253
            .extract_policy(&self.change_signers, BuildSatisfaction::None, &self.secp)?
145✔
1254
            .unwrap();
145✔
1255

145✔
1256
        // The policy allows spending external outputs, but it requires a policy path that hasn't been
145✔
1257
        // provided
145✔
1258
        if params.change_policy != tx_builder::ChangeSpendPolicy::OnlyChange
145✔
1259
            && external_policy.requires_path()
144✔
1260
            && params.external_policy_path.is_none()
4✔
1261
        {
1262
            return Err(CreateTxError::SpendingPolicyRequired(
1✔
1263
                KeychainKind::External,
1✔
1264
            ));
1✔
1265
        };
144✔
1266
        // Same for the internal_policy path
144✔
1267
        if params.change_policy != tx_builder::ChangeSpendPolicy::ChangeForbidden
144✔
1268
            && internal_policy.requires_path()
143✔
UNCOV
1269
            && params.internal_policy_path.is_none()
×
1270
        {
UNCOV
1271
            return Err(CreateTxError::SpendingPolicyRequired(
×
1272
                KeychainKind::Internal,
×
UNCOV
1273
            ));
×
1274
        };
144✔
1275

1276
        let external_requirements = external_policy.get_condition(
144✔
1277
            params
144✔
1278
                .external_policy_path
144✔
1279
                .as_ref()
144✔
1280
                .unwrap_or(&BTreeMap::new()),
144✔
1281
        )?;
144✔
1282
        let internal_requirements = internal_policy.get_condition(
144✔
1283
            params
144✔
1284
                .internal_policy_path
144✔
1285
                .as_ref()
144✔
1286
                .unwrap_or(&BTreeMap::new()),
144✔
1287
        )?;
144✔
1288

1289
        let requirements = external_requirements.merge(&internal_requirements)?;
144✔
1290

1291
        let version = match params.version {
142✔
1292
            Some(tx_builder::Version(0)) => return Err(CreateTxError::Version0),
1✔
1293
            Some(tx_builder::Version(1)) if requirements.csv.is_some() => {
18✔
1294
                return Err(CreateTxError::Version1Csv)
1✔
1295
            }
1296
            Some(tx_builder::Version(x)) => x,
18✔
1297
            None if requirements.csv.is_some() => 2,
124✔
1298
            None => 1,
120✔
1299
        };
1300

1301
        // We use a match here instead of a unwrap_or_else as it's way more readable :)
1302
        let current_height = match params.current_height {
142✔
1303
            // If they didn't tell us the current height, we assume it's the latest sync height.
1304
            None => {
1305
                let tip_height = self.chain.tip().height();
138✔
1306
                absolute::LockTime::from_height(tip_height).expect("invalid height")
138✔
1307
            }
1308
            Some(h) => h,
4✔
1309
        };
1310

1311
        let lock_time = match params.locktime {
141✔
1312
            // When no nLockTime is specified, we try to prevent fee sniping, if possible
1313
            None => {
1314
                // Fee sniping can be partially prevented by setting the timelock
1315
                // to current_height. If we don't know the current_height,
1316
                // we default to 0.
1317
                let fee_sniping_height = current_height;
139✔
1318

1319
                // We choose the biggest between the required nlocktime and the fee sniping
1320
                // height
1321
                match requirements.timelock {
4✔
1322
                    // No requirement, just use the fee_sniping_height
1323
                    None => fee_sniping_height,
135✔
1324
                    // There's a block-based requirement, but the value is lower than the fee_sniping_height
1325
                    Some(value @ absolute::LockTime::Blocks(_)) if value < fee_sniping_height => {
4✔
UNCOV
1326
                        fee_sniping_height
×
1327
                    }
1328
                    // There's a time-based requirement or a block-based requirement greater
1329
                    // than the fee_sniping_height use that value
1330
                    Some(value) => value,
4✔
1331
                }
1332
            }
1333
            // Specific nLockTime required and we have no constraints, so just set to that value
1334
            Some(x) if requirements.timelock.is_none() => x,
3✔
1335
            // Specific nLockTime required and it's compatible with the constraints
1336
            Some(x)
1✔
1337
                if requirements.timelock.unwrap().is_same_unit(x)
2✔
1338
                    && x >= requirements.timelock.unwrap() =>
2✔
1339
            {
1✔
1340
                x
1✔
1341
            }
1342
            // Invalid nLockTime required
1343
            Some(x) => {
1✔
1344
                return Err(CreateTxError::LockTime {
1✔
1345
                    requested: x,
1✔
1346
                    required: requirements.timelock.unwrap(),
1✔
1347
                })
1✔
1348
            }
1349
        };
1350

1351
        // The nSequence to be by default for inputs unless an explicit sequence is specified.
1352
        let n_sequence = match (params.rbf, requirements.csv) {
141✔
1353
            // No RBF or CSV but there's an nLockTime, so the nSequence cannot be final
1354
            (None, None) if lock_time != absolute::LockTime::ZERO => {
116✔
1355
                Sequence::ENABLE_LOCKTIME_NO_RBF
115✔
1356
            }
1357
            // No RBF, CSV or nLockTime, make the transaction final
1358
            (None, None) => Sequence::MAX,
1✔
1359

1360
            // No RBF requested, use the value from CSV. Note that this value is by definition
1361
            // non-final, so even if a timelock is enabled this nSequence is fine, hence why we
1362
            // don't bother checking for it here. The same is true for all the other branches below
1363
            (None, Some(csv)) => csv,
2✔
1364

1365
            // RBF with a specific value but that value is too high
1366
            (Some(tx_builder::RbfValue::Value(rbf)), _) if !rbf.is_rbf() => {
3✔
1367
                return Err(CreateTxError::RbfSequence)
1✔
1368
            }
1369
            // RBF with a specific value requested, but the value is incompatible with CSV
1370
            (Some(tx_builder::RbfValue::Value(rbf)), Some(csv))
1✔
1371
                if !check_nsequence_rbf(rbf, csv) =>
1✔
1372
            {
1✔
1373
                return Err(CreateTxError::RbfSequenceCsv { rbf, csv })
1✔
1374
            }
1375

1376
            // RBF enabled with the default value with CSV also enabled. CSV takes precedence
1377
            (Some(tx_builder::RbfValue::Default), Some(csv)) => csv,
1✔
1378
            // Valid RBF, either default or with a specific value. We ignore the `CSV` value
1379
            // because we've already checked it before
1380
            (Some(rbf), _) => rbf.get_value(),
20✔
1381
        };
1382

1383
        let (fee_rate, mut fee_amount) = match params.fee_policy.unwrap_or_default() {
139✔
1384
            //FIXME: see https://github.com/bitcoindevkit/bdk/issues/256
1385
            FeePolicy::FeeAmount(fee) => {
9✔
1386
                if let Some(previous_fee) = params.bumping_fee {
9✔
1387
                    if fee < previous_fee.absolute {
6✔
1388
                        return Err(CreateTxError::FeeTooLow {
2✔
1389
                            required: Amount::from_sat(previous_fee.absolute),
2✔
1390
                        });
2✔
1391
                    }
4✔
1392
                }
3✔
1393
                (FeeRate::ZERO, fee)
7✔
1394
            }
1395
            FeePolicy::FeeRate(rate) => {
130✔
1396
                if let Some(previous_fee) = params.bumping_fee {
130✔
1397
                    let required_feerate = FeeRate::from_sat_per_kwu(
11✔
1398
                        previous_fee.rate.to_sat_per_kwu()
11✔
1399
                            + FeeRate::BROADCAST_MIN.to_sat_per_kwu(), // +1 sat/vb
11✔
1400
                    );
11✔
1401
                    if rate < required_feerate {
11✔
1402
                        return Err(CreateTxError::FeeRateTooLow {
1✔
1403
                            required: required_feerate,
1✔
1404
                        });
1✔
1405
                    }
10✔
1406
                }
119✔
1407
                (rate, 0)
129✔
1408
            }
1409
        };
1410

1411
        let mut tx = Transaction {
136✔
1412
            version: transaction::Version::non_standard(version),
136✔
1413
            lock_time,
136✔
1414
            input: vec![],
136✔
1415
            output: vec![],
136✔
1416
        };
136✔
1417

136✔
1418
        if params.manually_selected_only && params.utxos.is_empty() {
136✔
1419
            return Err(CreateTxError::NoUtxosSelected);
1✔
1420
        }
135✔
1421

135✔
1422
        let mut outgoing = Amount::ZERO;
135✔
1423
        let mut received = Amount::ZERO;
135✔
1424

135✔
1425
        let recipients = params.recipients.iter().map(|(r, v)| (r, *v));
135✔
1426

1427
        for (index, (script_pubkey, value)) in recipients.enumerate() {
135✔
1428
            if !params.allow_dust && value.is_dust(script_pubkey) && !script_pubkey.is_op_return() {
85✔
1429
                return Err(CreateTxError::OutputBelowDustLimit(index));
1✔
1430
            }
84✔
1431

84✔
1432
            if self.is_mine(script_pubkey) {
84✔
1433
                received += Amount::from_sat(value);
42✔
1434
            }
46✔
1435

1436
            let new_out = TxOut {
84✔
1437
                script_pubkey: script_pubkey.clone(),
84✔
1438
                value: Amount::from_sat(value),
84✔
1439
            };
84✔
1440

84✔
1441
            tx.output.push(new_out);
84✔
1442

84✔
1443
            outgoing += Amount::from_sat(value);
84✔
1444
        }
1445

1446
        fee_amount += (fee_rate * tx.weight()).to_sat();
134✔
1447

134✔
1448
        let (required_utxos, optional_utxos) =
134✔
1449
            self.preselect_utxos(&params, Some(current_height.to_consensus_u32()));
134✔
1450

1451
        // get drain script
1452
        let drain_script = match params.drain_to {
134✔
1453
            Some(ref drain_recipient) => drain_recipient.clone(),
52✔
1454
            None => {
1455
                let change_keychain = KeychainKind::Internal;
82✔
1456
                let ((index, spk), index_changeset) = self
82✔
1457
                    .indexed_graph
82✔
1458
                    .index
82✔
1459
                    .next_unused_spk(&change_keychain)
82✔
1460
                    .expect("keychain must exist");
82✔
1461
                self.indexed_graph.index.mark_used(change_keychain, index);
82✔
1462
                self.stage.append(index_changeset.into());
82✔
1463
                spk
82✔
1464
            }
1465
        };
1466

1467
        let (required_utxos, optional_utxos) =
134✔
1468
            coin_selection::filter_duplicates(required_utxos, optional_utxos);
134✔
1469

1470
        let coin_selection = match coin_selection.coin_select(
134✔
1471
            required_utxos.clone(),
134✔
1472
            optional_utxos.clone(),
134✔
1473
            fee_rate,
134✔
1474
            outgoing.to_sat() + fee_amount,
134✔
1475
            &drain_script,
134✔
1476
        ) {
134✔
1477
            Ok(res) => res,
62✔
1478
            Err(e) => match e {
72✔
1479
                coin_selection::Error::InsufficientFunds { .. } => {
1480
                    return Err(CreateTxError::CoinSelection(e));
7✔
1481
                }
1482
                coin_selection::Error::BnBNoExactMatch
1483
                | coin_selection::Error::BnBTotalTriesExceeded => {
1484
                    coin_selection::single_random_draw(
65✔
1485
                        required_utxos,
65✔
1486
                        optional_utxos,
65✔
1487
                        outgoing.to_sat() + fee_amount,
65✔
1488
                        &drain_script,
65✔
1489
                        fee_rate,
65✔
1490
                        rng,
65✔
1491
                    )
65✔
1492
                }
1493
            },
1494
        };
1495
        fee_amount += coin_selection.fee_amount;
127✔
1496
        let excess = &coin_selection.excess;
127✔
1497

127✔
1498
        tx.input = coin_selection
127✔
1499
            .selected
127✔
1500
            .iter()
127✔
1501
            .map(|u| bitcoin::TxIn {
143✔
1502
                previous_output: u.outpoint(),
143✔
1503
                script_sig: ScriptBuf::default(),
143✔
1504
                sequence: u.sequence().unwrap_or(n_sequence),
143✔
1505
                witness: Witness::new(),
143✔
1506
            })
143✔
1507
            .collect();
127✔
1508

127✔
1509
        if tx.output.is_empty() {
127✔
1510
            // Uh oh, our transaction has no outputs.
1511
            // We allow this when:
1512
            // - We have a drain_to address and the utxos we must spend (this happens,
1513
            // for example, when we RBF)
1514
            // - We have a drain_to address and drain_wallet set
1515
            // Otherwise, we don't know who we should send the funds to, and how much
1516
            // we should send!
1517
            if params.drain_to.is_some() && (params.drain_wallet || !params.utxos.is_empty()) {
50✔
1518
                if let NoChange {
1519
                    dust_threshold,
1✔
1520
                    remaining_amount,
1✔
1521
                    change_fee,
1✔
1522
                } = excess
48✔
1523
                {
1524
                    return Err(CreateTxError::CoinSelection(Error::InsufficientFunds {
1✔
1525
                        needed: *dust_threshold,
1✔
1526
                        available: remaining_amount.saturating_sub(*change_fee),
1✔
1527
                    }));
1✔
1528
                }
47✔
1529
            } else {
1530
                return Err(CreateTxError::NoRecipients);
2✔
1531
            }
1532
        }
77✔
1533

1534
        match excess {
124✔
1535
            NoChange {
1536
                remaining_amount, ..
3✔
1537
            } => fee_amount += remaining_amount,
3✔
1538
            Change { amount, fee } => {
121✔
1539
                if self.is_mine(&drain_script) {
121✔
1540
                    received += Amount::from_sat(*amount);
111✔
1541
                }
111✔
1542
                fee_amount += fee;
121✔
1543

121✔
1544
                // create drain output
121✔
1545
                let drain_output = TxOut {
121✔
1546
                    value: Amount::from_sat(*amount),
121✔
1547
                    script_pubkey: drain_script,
121✔
1548
                };
121✔
1549

121✔
1550
                // TODO: We should pay attention when adding a new output: this might increase
121✔
1551
                // the length of the "number of vouts" parameter by 2 bytes, potentially making
121✔
1552
                // our feerate too low
121✔
1553
                tx.output.push(drain_output);
121✔
1554
            }
1555
        };
1556

1557
        // sort input/outputs according to the chosen algorithm
1558
        params.ordering.sort_tx_with_aux_rand(&mut tx, rng);
124✔
1559

1560
        let psbt = self.complete_transaction(tx, coin_selection.selected, params)?;
124✔
1561
        Ok(psbt)
122✔
1562
    }
145✔
1563

1564
    /// Bump the fee of a transaction previously created with this wallet.
1565
    ///
1566
    /// Returns an error if the transaction is already confirmed or doesn't explicitly signal
1567
    /// *replace by fee* (RBF). If the transaction can be fee bumped then it returns a [`TxBuilder`]
1568
    /// pre-populated with the inputs and outputs of the original transaction.
1569
    ///
1570
    /// ## Example
1571
    ///
1572
    /// ```no_run
1573
    /// # // TODO: remove norun -- bumping fee seems to need the tx in the wallet database first.
1574
    /// # use std::str::FromStr;
1575
    /// # use bitcoin::*;
1576
    /// # use bdk_wallet::*;
1577
    /// # use bdk_wallet::wallet::ChangeSet;
1578
    /// # use bdk_wallet::wallet::error::CreateTxError;
1579
    /// # use anyhow::Error;
1580
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1581
    /// # let mut wallet = doctest_wallet!();
1582
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1583
    /// let mut psbt = {
1584
    ///     let mut builder = wallet.build_tx();
1585
    ///     builder
1586
    ///         .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000))
1587
    ///         .enable_rbf();
1588
    ///     builder.finish()?
1589
    /// };
1590
    /// let _ = wallet.sign(&mut psbt, SignOptions::default())?;
1591
    /// let tx = psbt.clone().extract_tx().expect("tx");
1592
    /// // broadcast tx but it's taking too long to confirm so we want to bump the fee
1593
    /// let mut psbt =  {
1594
    ///     let mut builder = wallet.build_fee_bump(tx.compute_txid())?;
1595
    ///     builder
1596
    ///         .fee_rate(FeeRate::from_sat_per_vb(5).expect("valid feerate"));
1597
    ///     builder.finish()?
1598
    /// };
1599
    ///
1600
    /// let _ = wallet.sign(&mut psbt, SignOptions::default())?;
1601
    /// let fee_bumped_tx = psbt.extract_tx();
1602
    /// // broadcast fee_bumped_tx to replace original
1603
    /// # Ok::<(), anyhow::Error>(())
1604
    /// ```
1605
    // TODO: support for merging multiple transactions while bumping the fees
1606
    pub fn build_fee_bump(
152✔
1607
        &mut self,
152✔
1608
        txid: Txid,
152✔
1609
    ) -> Result<TxBuilder<'_, DefaultCoinSelectionAlgorithm>, BuildFeeBumpError> {
152✔
1610
        let graph = self.indexed_graph.graph();
152✔
1611
        let txout_index = &self.indexed_graph.index;
152✔
1612
        let chain_tip = self.chain.tip().block_id();
152✔
1613

1614
        let mut tx = graph
152✔
1615
            .get_tx(txid)
152✔
1616
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?
152✔
1617
            .as_ref()
152✔
1618
            .clone();
152✔
1619

1620
        let pos = graph
152✔
1621
            .get_chain_position(&self.chain, chain_tip, txid)
152✔
1622
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?;
152✔
1623
        if let ChainPosition::Confirmed(_) = pos {
152✔
1624
            return Err(BuildFeeBumpError::TransactionConfirmed(txid));
8✔
1625
        }
144✔
1626

144✔
1627
        if !tx
144✔
1628
            .input
144✔
1629
            .iter()
144✔
1630
            .any(|txin| txin.sequence.to_consensus_u32() <= 0xFFFFFFFD)
144✔
1631
        {
1632
            return Err(BuildFeeBumpError::IrreplaceableTransaction(
8✔
1633
                tx.compute_txid(),
8✔
1634
            ));
8✔
1635
        }
136✔
1636

1637
        let fee = self
136✔
1638
            .calculate_fee(&tx)
136✔
1639
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1640
        let fee_rate = self
136✔
1641
            .calculate_fee_rate(&tx)
136✔
1642
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1643

1644
        // remove the inputs from the tx and process them
1645
        let original_txin = tx.input.drain(..).collect::<Vec<_>>();
136✔
1646
        let original_utxos = original_txin
136✔
1647
            .iter()
136✔
1648
            .map(|txin| -> Result<_, BuildFeeBumpError> {
144✔
1649
                let prev_tx = graph
144✔
1650
                    .get_tx(txin.previous_output.txid)
144✔
1651
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?;
144✔
1652
                let txout = &prev_tx.output[txin.previous_output.vout as usize];
144✔
1653

1654
                let confirmation_time: ConfirmationTime = graph
144✔
1655
                    .get_chain_position(&self.chain, chain_tip, txin.previous_output.txid)
144✔
1656
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?
144✔
1657
                    .cloned()
144✔
1658
                    .into();
144✔
1659

1660
                let weighted_utxo = match txout_index.index_of_spk(&txout.script_pubkey) {
144✔
1661
                    Some(&(keychain, derivation_index)) => {
144✔
1662
                        let satisfaction_weight = self
144✔
1663
                            .get_descriptor_for_keychain(keychain)
144✔
1664
                            .max_weight_to_satisfy()
144✔
1665
                            .unwrap()
144✔
1666
                            .to_wu() as usize;
144✔
1667
                        WeightedUtxo {
144✔
1668
                            utxo: Utxo::Local(LocalOutput {
144✔
1669
                                outpoint: txin.previous_output,
144✔
1670
                                txout: txout.clone(),
144✔
1671
                                keychain,
144✔
1672
                                is_spent: true,
144✔
1673
                                derivation_index,
144✔
1674
                                confirmation_time,
144✔
1675
                            }),
144✔
1676
                            satisfaction_weight,
144✔
1677
                        }
144✔
1678
                    }
1679
                    None => {
UNCOV
1680
                        let satisfaction_weight =
×
UNCOV
1681
                            serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len();
×
UNCOV
1682
                        WeightedUtxo {
×
1683
                            utxo: Utxo::Foreign {
×
1684
                                outpoint: txin.previous_output,
×
1685
                                sequence: Some(txin.sequence),
×
1686
                                psbt_input: Box::new(psbt::Input {
×
1687
                                    witness_utxo: Some(txout.clone()),
×
1688
                                    non_witness_utxo: Some(prev_tx.as_ref().clone()),
×
1689
                                    ..Default::default()
×
1690
                                }),
×
1691
                            },
×
1692
                            satisfaction_weight,
×
1693
                        }
×
1694
                    }
1695
                };
1696

1697
                Ok(weighted_utxo)
144✔
1698
            })
144✔
1699
            .collect::<Result<Vec<_>, _>>()?;
136✔
1700

1701
        if tx.output.len() > 1 {
136✔
1702
            let mut change_index = None;
80✔
1703
            for (index, txout) in tx.output.iter().enumerate() {
160✔
1704
                let change_keychain = KeychainKind::Internal;
160✔
1705
                match txout_index.index_of_spk(&txout.script_pubkey) {
160✔
1706
                    Some((keychain, _)) if *keychain == change_keychain => {
104✔
1707
                        change_index = Some(index)
80✔
1708
                    }
1709
                    _ => {}
80✔
1710
                }
1711
            }
1712

1713
            if let Some(change_index) = change_index {
80✔
1714
                tx.output.remove(change_index);
80✔
1715
            }
80✔
1716
        }
56✔
1717

1718
        let params = TxParams {
136✔
1719
            // TODO: figure out what rbf option should be?
136✔
1720
            version: Some(tx_builder::Version(tx.version.0)),
136✔
1721
            recipients: tx
136✔
1722
                .output
136✔
1723
                .into_iter()
136✔
1724
                .map(|txout| (txout.script_pubkey, txout.value.to_sat()))
136✔
1725
                .collect(),
136✔
1726
            utxos: original_utxos,
136✔
1727
            bumping_fee: Some(tx_builder::PreviousFee {
136✔
1728
                absolute: fee.to_sat(),
136✔
1729
                rate: fee_rate,
136✔
1730
            }),
136✔
1731
            ..Default::default()
136✔
1732
        };
136✔
1733

136✔
1734
        Ok(TxBuilder {
136✔
1735
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
136✔
1736
            params,
136✔
1737
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
136✔
1738
        })
136✔
1739
    }
152✔
1740

1741
    /// Sign a transaction with all the wallet's signers, in the order specified by every signer's
1742
    /// [`SignerOrdering`]. This function returns the `Result` type with an encapsulated `bool` that has the value true if the PSBT was finalized, or false otherwise.
1743
    ///
1744
    /// The [`SignOptions`] can be used to tweak the behavior of the software signers, and the way
1745
    /// the transaction is finalized at the end. Note that it can't be guaranteed that *every*
1746
    /// signers will follow the options, but the "software signers" (WIF keys and `xprv`) defined
1747
    /// in this library will.
1748
    ///
1749
    /// ## Example
1750
    ///
1751
    /// ```
1752
    /// # use std::str::FromStr;
1753
    /// # use bitcoin::*;
1754
    /// # use bdk_wallet::*;
1755
    /// # use bdk_wallet::wallet::ChangeSet;
1756
    /// # use bdk_wallet::wallet::error::CreateTxError;
1757
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1758
    /// # let mut wallet = doctest_wallet!();
1759
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1760
    /// let mut psbt = {
1761
    ///     let mut builder = wallet.build_tx();
1762
    ///     builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
1763
    ///     builder.finish()?
1764
    /// };
1765
    /// let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
1766
    /// assert!(finalized, "we should have signed all the inputs");
1767
    /// # Ok::<(),anyhow::Error>(())
1768
    pub fn sign(&self, psbt: &mut Psbt, sign_options: SignOptions) -> Result<bool, SignerError> {
336✔
1769
        // This adds all the PSBT metadata for the inputs, which will help us later figure out how
336✔
1770
        // to derive our keys
336✔
1771
        self.update_psbt_with_descriptor(psbt)
336✔
1772
            .map_err(SignerError::MiniscriptPsbt)?;
336✔
1773

1774
        // If we aren't allowed to use `witness_utxo`, ensure that every input (except p2tr and finalized ones)
1775
        // has the `non_witness_utxo`
1776
        if !sign_options.trust_witness_utxo
336✔
1777
            && psbt
288✔
1778
                .inputs
288✔
1779
                .iter()
288✔
1780
                .filter(|i| i.final_script_witness.is_none() && i.final_script_sig.is_none())
296✔
1781
                .filter(|i| i.tap_internal_key.is_none() && i.tap_merkle_root.is_none())
288✔
1782
                .any(|i| i.non_witness_utxo.is_none())
288✔
1783
        {
UNCOV
1784
            return Err(SignerError::MissingNonWitnessUtxo);
×
1785
        }
336✔
1786

336✔
1787
        // If the user hasn't explicitly opted-in, refuse to sign the transaction unless every input
336✔
1788
        // is using `SIGHASH_ALL` or `SIGHASH_DEFAULT` for taproot
336✔
1789
        if !sign_options.allow_all_sighashes
336✔
1790
            && !psbt.inputs.iter().all(|i| {
344✔
1791
                i.sighash_type.is_none()
344✔
1792
                    || i.sighash_type == Some(EcdsaSighashType::All.into())
24✔
1793
                    || i.sighash_type == Some(TapSighashType::All.into())
16✔
1794
                    || i.sighash_type == Some(TapSighashType::Default.into())
16✔
1795
            })
344✔
1796
        {
1797
            return Err(SignerError::NonStandardSighash);
16✔
1798
        }
320✔
1799

1800
        for signer in self
664✔
1801
            .signers
320✔
1802
            .signers()
320✔
1803
            .iter()
320✔
1804
            .chain(self.change_signers.signers().iter())
320✔
1805
        {
1806
            signer.sign_transaction(psbt, &sign_options, &self.secp)?;
664✔
1807
        }
1808

1809
        // attempt to finalize
1810
        if sign_options.try_finalize {
288✔
1811
            self.finalize_psbt(psbt, sign_options)
248✔
1812
        } else {
1813
            Ok(false)
40✔
1814
        }
1815
    }
336✔
1816

1817
    /// Return the spending policies for the wallet's descriptor
1818
    pub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, DescriptorError> {
24✔
1819
        let signers = match keychain {
24✔
1820
            KeychainKind::External => &self.signers,
24✔
UNCOV
1821
            KeychainKind::Internal => &self.change_signers,
×
1822
        };
1823

1824
        self.public_descriptor(keychain).extract_policy(
24✔
1825
            signers,
24✔
1826
            BuildSatisfaction::None,
24✔
1827
            &self.secp,
24✔
1828
        )
24✔
1829
    }
24✔
1830

1831
    /// Return the "public" version of the wallet's descriptor, meaning a new descriptor that has
1832
    /// the same structure but with every secret key removed
1833
    ///
1834
    /// This can be used to build a watch-only version of a wallet
1835
    pub fn public_descriptor(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,196✔
1836
        self.indexed_graph
6,196✔
1837
            .index
6,196✔
1838
            .keychains()
6,196✔
1839
            .find(|(k, _)| *k == &keychain)
7,026✔
1840
            .map(|(_, d)| d)
6,196✔
1841
            .expect("keychain must exist")
6,196✔
1842
    }
6,196✔
1843

1844
    /// Finalize a PSBT, i.e., for each input determine if sufficient data is available to pass
1845
    /// validation and construct the respective `scriptSig` or `scriptWitness`. Please refer to
1846
    /// [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#Input_Finalizer),
1847
    /// and [BIP371](https://github.com/bitcoin/bips/blob/master/bip-0371.mediawiki)
1848
    /// for further information.
1849
    ///
1850
    /// Returns `true` if the PSBT could be finalized, and `false` otherwise.
1851
    ///
1852
    /// The [`SignOptions`] can be used to tweak the behavior of the finalizer.
1853
    pub fn finalize_psbt(
248✔
1854
        &self,
248✔
1855
        psbt: &mut Psbt,
248✔
1856
        sign_options: SignOptions,
248✔
1857
    ) -> Result<bool, SignerError> {
248✔
1858
        let chain_tip = self.chain.tip().block_id();
248✔
1859

248✔
1860
        let tx = &psbt.unsigned_tx;
248✔
1861
        let mut finished = true;
248✔
1862

1863
        for (n, input) in tx.input.iter().enumerate() {
288✔
1864
            let psbt_input = &psbt
288✔
1865
                .inputs
288✔
1866
                .get(n)
288✔
1867
                .ok_or(SignerError::InputIndexOutOfRange)?;
288✔
1868
            if psbt_input.final_script_sig.is_some() || psbt_input.final_script_witness.is_some() {
280✔
1869
                continue;
16✔
1870
            }
264✔
1871
            let confirmation_height = self
264✔
1872
                .indexed_graph
264✔
1873
                .graph()
264✔
1874
                .get_chain_position(&self.chain, chain_tip, input.previous_output.txid)
264✔
1875
                .map(|chain_position| match chain_position {
264✔
1876
                    ChainPosition::Confirmed(a) => a.confirmation_height,
240✔
UNCOV
1877
                    ChainPosition::Unconfirmed(_) => u32::MAX,
×
1878
                });
264✔
1879
            let current_height = sign_options
264✔
1880
                .assume_height
264✔
1881
                .unwrap_or_else(|| self.chain.tip().height());
264✔
1882

264✔
1883
            // - Try to derive the descriptor by looking at the txout. If it's in our database, we
264✔
1884
            //   know exactly which `keychain` to use, and which derivation index it is
264✔
1885
            // - If that fails, try to derive it by looking at the psbt input: the complete logic
264✔
1886
            //   is in `src/descriptor/mod.rs`, but it will basically look at `bip32_derivation`,
264✔
1887
            //   `redeem_script` and `witness_script` to determine the right derivation
264✔
1888
            // - If that also fails, it will try it on the internal descriptor, if present
264✔
1889
            let desc = psbt
264✔
1890
                .get_utxo_for(n)
264✔
1891
                .and_then(|txout| self.get_descriptor_for_txout(&txout))
264✔
1892
                .or_else(|| {
264✔
1893
                    self.indexed_graph.index.keychains().find_map(|(_, desc)| {
32✔
1894
                        desc.derive_from_psbt_input(psbt_input, psbt.get_utxo_for(n), &self.secp)
32✔
1895
                    })
32✔
1896
                });
264✔
1897

264✔
1898
            match desc {
264✔
1899
                Some(desc) => {
248✔
1900
                    let mut tmp_input = bitcoin::TxIn::default();
248✔
1901
                    match desc.satisfy(
248✔
1902
                        &mut tmp_input,
248✔
1903
                        (
248✔
1904
                            PsbtInputSatisfier::new(psbt, n),
248✔
1905
                            After::new(Some(current_height), false),
248✔
1906
                            Older::new(Some(current_height), confirmation_height, false),
248✔
1907
                        ),
248✔
1908
                    ) {
248✔
1909
                        Ok(_) => {
1910
                            // Set the UTXO fields, final script_sig and witness
1911
                            // and clear everything else.
1912
                            let original = mem::take(&mut psbt.inputs[n]);
240✔
1913
                            let psbt_input = &mut psbt.inputs[n];
240✔
1914
                            psbt_input.non_witness_utxo = original.non_witness_utxo;
240✔
1915
                            psbt_input.witness_utxo = original.witness_utxo;
240✔
1916
                            if !tmp_input.script_sig.is_empty() {
240✔
1917
                                psbt_input.final_script_sig = Some(tmp_input.script_sig);
16✔
1918
                            }
224✔
1919
                            if !tmp_input.witness.is_empty() {
240✔
1920
                                psbt_input.final_script_witness = Some(tmp_input.witness);
232✔
1921
                            }
232✔
1922
                        }
1923
                        Err(_) => finished = false,
8✔
1924
                    }
1925
                }
1926
                None => finished = false,
16✔
1927
            }
1928
        }
1929

1930
        // Clear derivation paths from outputs
1931
        if finished {
240✔
1932
            for output in &mut psbt.outputs {
520✔
1933
                output.bip32_derivation.clear();
304✔
1934
                output.tap_key_origins.clear();
304✔
1935
            }
304✔
1936
        }
24✔
1937

1938
        Ok(finished)
240✔
1939
    }
248✔
1940

1941
    /// Return the secp256k1 context used for all signing operations
1942
    pub fn secp_ctx(&self) -> &SecpCtx {
28✔
1943
        &self.secp
28✔
1944
    }
28✔
1945

1946
    /// Returns the descriptor used to create addresses for a particular `keychain`.
1947
    pub fn get_descriptor_for_keychain(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,028✔
1948
        self.public_descriptor(keychain)
6,028✔
1949
    }
6,028✔
1950

1951
    /// The derivation index of this wallet. It will return `None` if it has not derived any addresses.
1952
    /// Otherwise, it will return the index of the highest address it has derived.
1953
    pub fn derivation_index(&self, keychain: KeychainKind) -> Option<u32> {
40✔
1954
        self.indexed_graph.index.last_revealed_index(&keychain)
40✔
1955
    }
40✔
1956

1957
    /// The index of the next address that you would get if you were to ask the wallet for a new address
UNCOV
1958
    pub fn next_derivation_index(&self, keychain: KeychainKind) -> u32 {
×
UNCOV
1959
        self.indexed_graph
×
UNCOV
1960
            .index
×
1961
            .next_index(&keychain)
×
1962
            .expect("keychain must exist")
×
1963
            .0
×
1964
    }
×
1965

1966
    /// Informs the wallet that you no longer intend to broadcast a tx that was built from it.
1967
    ///
1968
    /// This frees up the change address used when creating the tx for use in future transactions.
1969
    // TODO: Make this free up reserved utxos when that's implemented
1970
    pub fn cancel_tx(&mut self, tx: &Transaction) {
16✔
1971
        let txout_index = &mut self.indexed_graph.index;
16✔
1972
        for txout in &tx.output {
48✔
1973
            if let Some((keychain, index)) = txout_index.index_of_spk(&txout.script_pubkey) {
32✔
1974
                // NOTE: unmark_used will **not** make something unused if it has actually been used
16✔
1975
                // by a tx in the tracker. It only removes the superficial marking.
16✔
1976
                txout_index.unmark_used(*keychain, *index);
16✔
1977
            }
16✔
1978
        }
1979
    }
16✔
1980

1981
    fn get_descriptor_for_txout(&self, txout: &TxOut) -> Option<DerivedDescriptor> {
264✔
1982
        let &(keychain, child) = self
264✔
1983
            .indexed_graph
264✔
1984
            .index
264✔
1985
            .index_of_spk(&txout.script_pubkey)?;
264✔
1986
        let descriptor = self.get_descriptor_for_keychain(keychain);
248✔
1987
        descriptor.at_derivation_index(child).ok()
248✔
1988
    }
264✔
1989

1990
    fn get_available_utxos(&self) -> Vec<(LocalOutput, usize)> {
1,128✔
1991
        self.list_unspent()
1,128✔
1992
            .map(|utxo| {
1,240✔
1993
                let keychain = utxo.keychain;
1,240✔
1994
                (utxo, {
1,240✔
1995
                    self.get_descriptor_for_keychain(keychain)
1,240✔
1996
                        .max_weight_to_satisfy()
1,240✔
1997
                        .unwrap()
1,240✔
1998
                        .to_wu() as usize
1,240✔
1999
                })
1,240✔
2000
            })
1,240✔
2001
            .collect()
1,128✔
2002
    }
1,128✔
2003

2004
    /// Given the options returns the list of utxos that must be used to form the
2005
    /// transaction and any further that may be used if needed.
2006
    fn preselect_utxos(
1,128✔
2007
        &self,
1,128✔
2008
        params: &TxParams,
1,128✔
2009
        current_height: Option<u32>,
1,128✔
2010
    ) -> (Vec<WeightedUtxo>, Vec<WeightedUtxo>) {
1,128✔
2011
        let TxParams {
1,128✔
2012
            change_policy,
1,128✔
2013
            unspendable,
1,128✔
2014
            utxos,
1,128✔
2015
            drain_wallet,
1,128✔
2016
            manually_selected_only,
1,128✔
2017
            bumping_fee,
1,128✔
2018
            ..
1,128✔
2019
        } = params;
1,128✔
2020

1,128✔
2021
        let manually_selected = utxos.clone();
1,128✔
2022
        // we mandate confirmed transactions if we're bumping the fee
1,128✔
2023
        let must_only_use_confirmed_tx = bumping_fee.is_some();
1,128✔
2024
        let must_use_all_available = *drain_wallet;
1,128✔
2025

1,128✔
2026
        let chain_tip = self.chain.tip().block_id();
1,128✔
2027
        //    must_spend <- manually selected utxos
1,128✔
2028
        //    may_spend  <- all other available utxos
1,128✔
2029
        let mut may_spend = self.get_available_utxos();
1,128✔
2030

1,128✔
2031
        may_spend.retain(|may_spend| {
1,240✔
2032
            !manually_selected
1,240✔
2033
                .iter()
1,240✔
2034
                .any(|manually_selected| manually_selected.utxo.outpoint() == may_spend.0.outpoint)
1,240✔
2035
        });
1,240✔
2036
        let mut must_spend = manually_selected;
1,128✔
2037

1,128✔
2038
        // NOTE: we are intentionally ignoring `unspendable` here. i.e manual
1,128✔
2039
        // selection overrides unspendable.
1,128✔
2040
        if *manually_selected_only {
1,128✔
2041
            return (must_spend, vec![]);
40✔
2042
        }
1,088✔
2043

1,088✔
2044
        let satisfies_confirmed = may_spend
1,088✔
2045
            .iter()
1,088✔
2046
            .map(|u| -> bool {
1,128✔
2047
                let txid = u.0.outpoint.txid;
1,128✔
2048
                let tx = match self.indexed_graph.graph().get_tx(txid) {
1,128✔
2049
                    Some(tx) => tx,
1,128✔
UNCOV
2050
                    None => return false,
×
2051
                };
2052
                let confirmation_time: ConfirmationTime = match self
1,128✔
2053
                    .indexed_graph
1,128✔
2054
                    .graph()
1,128✔
2055
                    .get_chain_position(&self.chain, chain_tip, txid)
1,128✔
2056
                {
2057
                    Some(chain_position) => chain_position.cloned().into(),
1,128✔
UNCOV
2058
                    None => return false,
×
2059
                };
2060

2061
                // Whether the UTXO is mature and, if needed, confirmed
2062
                let mut spendable = true;
1,128✔
2063
                if must_only_use_confirmed_tx && !confirmation_time.is_confirmed() {
1,128✔
2064
                    return false;
64✔
2065
                }
1,064✔
2066
                if tx.is_coinbase() {
1,064✔
2067
                    debug_assert!(
24✔
2068
                        confirmation_time.is_confirmed(),
24✔
UNCOV
2069
                        "coinbase must always be confirmed"
×
2070
                    );
2071
                    if let Some(current_height) = current_height {
24✔
2072
                        match confirmation_time {
24✔
2073
                            ConfirmationTime::Confirmed { height, .. } => {
24✔
2074
                                // https://github.com/bitcoin/bitcoin/blob/c5e67be03bb06a5d7885c55db1f016fbf2333fe3/src/validation.cpp#L373-L375
24✔
2075
                                spendable &=
24✔
2076
                                    (current_height.saturating_sub(height)) >= COINBASE_MATURITY;
24✔
2077
                            }
24✔
UNCOV
2078
                            ConfirmationTime::Unconfirmed { .. } => spendable = false,
×
2079
                        }
UNCOV
2080
                    }
×
2081
                }
1,040✔
2082
                spendable
1,064✔
2083
            })
1,128✔
2084
            .collect::<Vec<_>>();
1,088✔
2085

1,088✔
2086
        let mut i = 0;
1,088✔
2087
        may_spend.retain(|u| {
1,128✔
2088
            let retain = change_policy.is_satisfied_by(&u.0)
1,128✔
2089
                && !unspendable.contains(&u.0.outpoint)
1,120✔
2090
                && satisfies_confirmed[i];
1,120✔
2091
            i += 1;
1,128✔
2092
            retain
1,128✔
2093
        });
1,128✔
2094

1,088✔
2095
        let mut may_spend = may_spend
1,088✔
2096
            .into_iter()
1,088✔
2097
            .map(|(local_utxo, satisfaction_weight)| WeightedUtxo {
1,088✔
2098
                satisfaction_weight,
1,040✔
2099
                utxo: Utxo::Local(local_utxo),
1,040✔
2100
            })
1,088✔
2101
            .collect();
1,088✔
2102

1,088✔
2103
        if must_use_all_available {
1,088✔
2104
            must_spend.append(&mut may_spend);
392✔
2105
        }
696✔
2106

2107
        (must_spend, may_spend)
1,088✔
2108
    }
1,128✔
2109

2110
    fn complete_transaction(
1,048✔
2111
        &self,
1,048✔
2112
        tx: Transaction,
1,048✔
2113
        selected: Vec<Utxo>,
1,048✔
2114
        params: TxParams,
1,048✔
2115
    ) -> Result<Psbt, CreateTxError> {
1,048✔
2116
        let mut psbt = Psbt::from_unsigned_tx(tx)?;
1,048✔
2117

2118
        if params.add_global_xpubs {
1,048✔
2119
            let all_xpubs = self
24✔
2120
                .keychains()
24✔
2121
                .flat_map(|(_, desc)| desc.get_extended_keys())
48✔
2122
                .collect::<Vec<_>>();
24✔
2123

2124
            for xpub in all_xpubs {
56✔
2125
                let origin = match xpub.origin {
32✔
2126
                    Some(origin) => origin,
24✔
2127
                    None if xpub.xkey.depth == 0 => {
16✔
2128
                        (xpub.root_fingerprint(&self.secp), vec![].into())
8✔
2129
                    }
2130
                    _ => return Err(CreateTxError::MissingKeyOrigin(xpub.xkey.to_string())),
8✔
2131
                };
2132

2133
                psbt.xpub.insert(xpub.xkey, origin);
32✔
2134
            }
2135
        }
1,024✔
2136

2137
        let mut lookup_output = selected
1,040✔
2138
            .into_iter()
1,040✔
2139
            .map(|utxo| (utxo.outpoint(), utxo))
1,168✔
2140
            .collect::<HashMap<_, _>>();
1,040✔
2141

2142
        // add metadata for the inputs
2143
        for (psbt_input, input) in psbt.inputs.iter_mut().zip(psbt.unsigned_tx.input.iter()) {
1,168✔
2144
            let utxo = match lookup_output.remove(&input.previous_output) {
1,168✔
2145
                Some(utxo) => utxo,
1,168✔
UNCOV
2146
                None => continue,
×
2147
            };
2148

2149
            match utxo {
1,168✔
2150
                Utxo::Local(utxo) => {
1,120✔
2151
                    *psbt_input =
1,120✔
2152
                        match self.get_psbt_input(utxo, params.sighash, params.only_witness_utxo) {
1,120✔
2153
                            Ok(psbt_input) => psbt_input,
1,120✔
UNCOV
2154
                            Err(e) => match e {
×
UNCOV
2155
                                CreateTxError::UnknownUtxo => psbt::Input {
×
UNCOV
2156
                                    sighash_type: params.sighash,
×
2157
                                    ..psbt::Input::default()
×
2158
                                },
×
2159
                                _ => return Err(e),
×
2160
                            },
2161
                        }
2162
                }
2163
                Utxo::Foreign {
2164
                    outpoint,
48✔
2165
                    psbt_input: foreign_psbt_input,
48✔
2166
                    ..
48✔
2167
                } => {
48✔
2168
                    let is_taproot = foreign_psbt_input
48✔
2169
                        .witness_utxo
48✔
2170
                        .as_ref()
48✔
2171
                        .map(|txout| txout.script_pubkey.is_p2tr())
48✔
2172
                        .unwrap_or(false);
48✔
2173
                    if !is_taproot
48✔
2174
                        && !params.only_witness_utxo
40✔
2175
                        && foreign_psbt_input.non_witness_utxo.is_none()
16✔
2176
                    {
2177
                        return Err(CreateTxError::MissingNonWitnessUtxo(outpoint));
8✔
2178
                    }
40✔
2179
                    *psbt_input = *foreign_psbt_input;
40✔
2180
                }
2181
            }
2182
        }
2183

2184
        self.update_psbt_with_descriptor(&mut psbt)?;
1,032✔
2185

2186
        Ok(psbt)
1,032✔
2187
    }
1,048✔
2188

2189
    /// get the corresponding PSBT Input for a LocalUtxo
2190
    pub fn get_psbt_input(
1,136✔
2191
        &self,
1,136✔
2192
        utxo: LocalOutput,
1,136✔
2193
        sighash_type: Option<psbt::PsbtSighashType>,
1,136✔
2194
        only_witness_utxo: bool,
1,136✔
2195
    ) -> Result<psbt::Input, CreateTxError> {
1,136✔
2196
        // Try to find the prev_script in our db to figure out if this is internal or external,
2197
        // and the derivation index
2198
        let &(keychain, child) = self
1,136✔
2199
            .indexed_graph
1,136✔
2200
            .index
1,136✔
2201
            .index_of_spk(&utxo.txout.script_pubkey)
1,136✔
2202
            .ok_or(CreateTxError::UnknownUtxo)?;
1,136✔
2203

2204
        let mut psbt_input = psbt::Input {
1,136✔
2205
            sighash_type,
1,136✔
2206
            ..psbt::Input::default()
1,136✔
2207
        };
1,136✔
2208

1,136✔
2209
        let desc = self.get_descriptor_for_keychain(keychain);
1,136✔
2210
        let derived_descriptor = desc
1,136✔
2211
            .at_derivation_index(child)
1,136✔
2212
            .expect("child can't be hardened");
1,136✔
2213

1,136✔
2214
        psbt_input
1,136✔
2215
            .update_with_descriptor_unchecked(&derived_descriptor)
1,136✔
2216
            .map_err(MiniscriptPsbtError::Conversion)?;
1,136✔
2217

2218
        let prev_output = utxo.outpoint;
1,136✔
2219
        if let Some(prev_tx) = self.indexed_graph.graph().get_tx(prev_output.txid) {
1,136✔
2220
            if desc.is_witness() || desc.is_taproot() {
1,136✔
2221
                psbt_input.witness_utxo = Some(prev_tx.output[prev_output.vout as usize].clone());
1,104✔
2222
            }
1,104✔
2223
            if !desc.is_taproot() && (!desc.is_witness() || !only_witness_utxo) {
1,136✔
2224
                psbt_input.non_witness_utxo = Some(prev_tx.as_ref().clone());
896✔
2225
            }
896✔
UNCOV
2226
        }
×
2227
        Ok(psbt_input)
1,136✔
2228
    }
1,136✔
2229

2230
    fn update_psbt_with_descriptor(&self, psbt: &mut Psbt) -> Result<(), MiniscriptPsbtError> {
1,368✔
2231
        // We need to borrow `psbt` mutably within the loops, so we have to allocate a vec for all
1,368✔
2232
        // the input utxos and outputs
1,368✔
2233
        let utxos = (0..psbt.inputs.len())
1,368✔
2234
            .filter_map(|i| psbt.get_utxo_for(i).map(|utxo| (true, i, utxo)))
1,536✔
2235
            .chain(
1,368✔
2236
                psbt.unsigned_tx
1,368✔
2237
                    .output
1,368✔
2238
                    .iter()
1,368✔
2239
                    .enumerate()
1,368✔
2240
                    .map(|(i, out)| (false, i, out.clone())),
2,168✔
2241
            )
1,368✔
2242
            .collect::<Vec<_>>();
1,368✔
2243

2244
        // Try to figure out the keychain and derivation for every input and output
2245
        for (is_input, index, out) in utxos.into_iter() {
3,664✔
2246
            if let Some(&(keychain, child)) =
3,088✔
2247
                self.indexed_graph.index.index_of_spk(&out.script_pubkey)
3,664✔
2248
            {
2249
                let desc = self.get_descriptor_for_keychain(keychain);
3,088✔
2250
                let desc = desc
3,088✔
2251
                    .at_derivation_index(child)
3,088✔
2252
                    .expect("child can't be hardened");
3,088✔
2253

3,088✔
2254
                if is_input {
3,088✔
2255
                    psbt.update_input_with_descriptor(index, &desc)
1,424✔
2256
                        .map_err(MiniscriptPsbtError::UtxoUpdate)?;
1,424✔
2257
                } else {
2258
                    psbt.update_output_with_descriptor(index, &desc)
1,664✔
2259
                        .map_err(MiniscriptPsbtError::OutputUpdate)?;
1,664✔
2260
                }
2261
            }
576✔
2262
        }
2263

2264
        Ok(())
1,368✔
2265
    }
1,368✔
2266

2267
    /// Return the checksum of the public descriptor associated to `keychain`
2268
    ///
2269
    /// Internally calls [`Self::get_descriptor_for_keychain`] to fetch the right descriptor
2270
    pub fn descriptor_checksum(&self, keychain: KeychainKind) -> String {
8✔
2271
        self.get_descriptor_for_keychain(keychain)
8✔
2272
            .to_string()
8✔
2273
            .split_once('#')
8✔
2274
            .unwrap()
8✔
2275
            .1
8✔
2276
            .to_string()
8✔
2277
    }
8✔
2278

2279
    /// Applies an update to the wallet and stages the changes (but does not persist them).
2280
    ///
2281
    /// Usually you create an `update` by interacting with some blockchain data source and inserting
2282
    /// transactions related to your wallet into it.
2283
    ///
2284
    /// After applying updates you should persist the staged wallet changes. For an example of how
2285
    /// to persist staged wallet changes see [`Wallet::reveal_next_address`]. `
2286
    ///
2287
    /// [`commit`]: Self::commit
UNCOV
2288
    pub fn apply_update(&mut self, update: impl Into<Update>) -> Result<(), CannotConnectError> {
×
UNCOV
2289
        let update = update.into();
×
UNCOV
2290
        let mut changeset = match update.chain {
×
2291
            Some(chain_update) => ChangeSet::from(self.chain.apply_update(chain_update)?),
×
2292
            None => ChangeSet::default(),
×
2293
        };
2294

2295
        let index_changeset = self
×
UNCOV
2296
            .indexed_graph
×
UNCOV
2297
            .index
×
2298
            .reveal_to_target_multi(&update.last_active_indices);
×
2299
        changeset.append(index_changeset.into());
×
2300
        changeset.append(self.indexed_graph.apply_update(update.graph).into());
×
2301
        self.stage.append(changeset);
×
2302
        Ok(())
×
2303
    }
×
2304

2305
    /// Get a reference of the staged [`ChangeSet`] that are yet to be committed (if any).
2306
    pub fn staged(&self) -> Option<&ChangeSet> {
×
UNCOV
2307
        if self.stage.is_empty() {
×
UNCOV
2308
            None
×
2309
        } else {
2310
            Some(&self.stage)
×
2311
        }
UNCOV
2312
    }
×
2313

2314
    /// Take the staged [`ChangeSet`] to be persisted now (if any).
2315
    pub fn take_staged(&mut self) -> Option<ChangeSet> {
32✔
2316
        self.stage.take()
32✔
2317
    }
32✔
2318

2319
    /// Get a reference to the inner [`TxGraph`].
UNCOV
2320
    pub fn tx_graph(&self) -> &TxGraph<ConfirmationTimeHeightAnchor> {
×
UNCOV
2321
        self.indexed_graph.graph()
×
UNCOV
2322
    }
×
2323

2324
    /// Get a reference to the inner [`KeychainTxOutIndex`].
2325
    pub fn spk_index(&self) -> &KeychainTxOutIndex<KeychainKind> {
48✔
2326
        &self.indexed_graph.index
48✔
2327
    }
48✔
2328

2329
    /// Get a reference to the inner [`LocalChain`].
UNCOV
2330
    pub fn local_chain(&self) -> &LocalChain {
×
UNCOV
2331
        &self.chain
×
UNCOV
2332
    }
×
2333

2334
    /// Introduces a `block` of `height` to the wallet, and tries to connect it to the
2335
    /// `prev_blockhash` of the block's header.
2336
    ///
2337
    /// This is a convenience method that is equivalent to calling [`apply_block_connected_to`]
2338
    /// with `prev_blockhash` and `height-1` as the `connected_to` parameter.
2339
    ///
2340
    /// [`apply_block_connected_to`]: Self::apply_block_connected_to
UNCOV
2341
    pub fn apply_block(&mut self, block: &Block, height: u32) -> Result<(), CannotConnectError> {
×
UNCOV
2342
        let connected_to = match height.checked_sub(1) {
×
UNCOV
2343
            Some(prev_height) => BlockId {
×
2344
                height: prev_height,
×
2345
                hash: block.header.prev_blockhash,
×
2346
            },
×
2347
            None => BlockId {
×
2348
                height,
×
2349
                hash: block.block_hash(),
×
2350
            },
×
2351
        };
2352
        self.apply_block_connected_to(block, height, connected_to)
×
2353
            .map_err(|err| match err {
×
2354
                ApplyHeaderError::InconsistentBlocks => {
2355
                    unreachable!("connected_to is derived from the block so must be consistent")
×
2356
                }
UNCOV
2357
                ApplyHeaderError::CannotConnect(err) => err,
×
2358
            })
×
UNCOV
2359
    }
×
2360

2361
    /// Applies relevant transactions from `block` of `height` to the wallet, and connects the
2362
    /// block to the internal chain.
2363
    ///
2364
    /// The `connected_to` parameter informs the wallet how this block connects to the internal
2365
    /// [`LocalChain`]. Relevant transactions are filtered from the `block` and inserted into the
2366
    /// internal [`TxGraph`].
2367
    ///
2368
    /// **WARNING**: You must persist the changes resulting from one or more calls to this method
2369
    /// if you need the inserted block data to be reloaded after closing the wallet.
2370
    /// See [`Wallet::reveal_next_address`].
UNCOV
2371
    pub fn apply_block_connected_to(
×
UNCOV
2372
        &mut self,
×
UNCOV
2373
        block: &Block,
×
2374
        height: u32,
×
2375
        connected_to: BlockId,
×
2376
    ) -> Result<(), ApplyHeaderError> {
×
2377
        let mut changeset = ChangeSet::default();
×
2378
        changeset.append(
×
2379
            self.chain
×
2380
                .apply_header_connected_to(&block.header, height, connected_to)?
×
2381
                .into(),
×
2382
        );
×
2383
        changeset.append(
×
2384
            self.indexed_graph
×
2385
                .apply_block_relevant(block, height)
×
2386
                .into(),
×
2387
        );
×
2388
        self.stage.append(changeset);
×
2389
        Ok(())
×
2390
    }
×
2391

2392
    /// Apply relevant unconfirmed transactions to the wallet.
2393
    ///
2394
    /// Transactions that are not relevant are filtered out.
2395
    ///
2396
    /// This method takes in an iterator of `(tx, last_seen)` where `last_seen` is the timestamp of
2397
    /// when the transaction was last seen in the mempool. This is used for conflict resolution
2398
    /// when there is conflicting unconfirmed transactions. The transaction with the later
2399
    /// `last_seen` is prioritized.
2400
    ///
2401
    /// **WARNING**: You must persist the changes resulting from one or more calls to this method
2402
    /// if you need the applied unconfirmed transactions to be reloaded after closing the wallet.
2403
    /// See [`Wallet::reveal_next_address`].
UNCOV
2404
    pub fn apply_unconfirmed_txs<'t>(
×
UNCOV
2405
        &mut self,
×
UNCOV
2406
        unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>,
×
2407
    ) {
×
2408
        let indexed_graph_changeset = self
×
2409
            .indexed_graph
×
2410
            .batch_insert_relevant_unconfirmed(unconfirmed_txs);
×
2411
        self.stage.append(indexed_graph_changeset.into());
×
2412
    }
×
2413
}
2414

2415
/// Methods to construct sync/full-scan requests for spk-based chain sources.
2416
impl Wallet {
2417
    /// Create a partial [`SyncRequest`] for this wallet for all revealed spks.
2418
    ///
2419
    /// This is the first step when performing a spk-based wallet partial sync, the returned
2420
    /// [`SyncRequest`] collects all revealed script pubkeys from the wallet keychain needed to
2421
    /// start a blockchain sync with a spk based blockchain client.
UNCOV
2422
    pub fn start_sync_with_revealed_spks(&self) -> SyncRequest {
×
UNCOV
2423
        SyncRequest::from_chain_tip(self.chain.tip())
×
UNCOV
2424
            .populate_with_revealed_spks(&self.indexed_graph.index, ..)
×
2425
    }
×
2426

2427
    /// Create a [`FullScanRequest] for this wallet.
2428
    ///
2429
    /// This is the first step when performing a spk-based wallet full scan, the returned
2430
    /// [`FullScanRequest] collects iterators for the wallet's keychain script pub keys needed to
2431
    /// start a blockchain full scan with a spk based blockchain client.
2432
    ///
2433
    /// This operation is generally only used when importing or restoring a previously used wallet
2434
    /// in which the list of used scripts is not known.
UNCOV
2435
    pub fn start_full_scan(&self) -> FullScanRequest<KeychainKind> {
×
UNCOV
2436
        FullScanRequest::from_keychain_txout_index(self.chain.tip(), &self.indexed_graph.index)
×
UNCOV
2437
    }
×
2438
}
2439

2440
impl AsRef<bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor>> for Wallet {
UNCOV
2441
    fn as_ref(&self) -> &bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor> {
×
UNCOV
2442
        self.indexed_graph.graph()
×
UNCOV
2443
    }
×
2444
}
2445

2446
/// Deterministically generate a unique name given the descriptors defining the wallet
2447
///
2448
/// Compatible with [`wallet_name_from_descriptor`]
UNCOV
2449
pub fn wallet_name_from_descriptor<T>(
×
UNCOV
2450
    descriptor: T,
×
UNCOV
2451
    change_descriptor: Option<T>,
×
2452
    network: Network,
×
2453
    secp: &SecpCtx,
×
2454
) -> Result<String, DescriptorError>
×
2455
where
×
2456
    T: IntoWalletDescriptor,
×
2457
{
×
2458
    //TODO check descriptors contains only public keys
2459
    let descriptor = descriptor
×
2460
        .into_wallet_descriptor(secp, network)?
×
2461
        .0
2462
        .to_string();
×
2463
    let mut wallet_name = calc_checksum(&descriptor[..descriptor.find('#').unwrap()])?;
×
UNCOV
2464
    if let Some(change_descriptor) = change_descriptor {
×
2465
        let change_descriptor = change_descriptor
×
2466
            .into_wallet_descriptor(secp, network)?
×
2467
            .0
2468
            .to_string();
×
2469
        wallet_name.push_str(
×
UNCOV
2470
            calc_checksum(&change_descriptor[..change_descriptor.find('#').unwrap()])?.as_str(),
×
2471
        );
2472
    }
×
2473

UNCOV
2474
    Ok(wallet_name)
×
2475
}
×
2476

2477
fn new_local_utxo(
1,392✔
2478
    keychain: KeychainKind,
1,392✔
2479
    derivation_index: u32,
1,392✔
2480
    full_txo: FullTxOut<ConfirmationTimeHeightAnchor>,
1,392✔
2481
) -> LocalOutput {
1,392✔
2482
    LocalOutput {
1,392✔
2483
        outpoint: full_txo.outpoint,
1,392✔
2484
        txout: full_txo.txout,
1,392✔
2485
        is_spent: full_txo.spent_by.is_some(),
1,392✔
2486
        confirmation_time: full_txo.chain_position.into(),
1,392✔
2487
        keychain,
1,392✔
2488
        derivation_index,
1,392✔
2489
    }
1,392✔
2490
}
1,392✔
2491

2492
fn create_signers<E: IntoWalletDescriptor>(
248✔
2493
    index: &mut KeychainTxOutIndex<KeychainKind>,
248✔
2494
    secp: &Secp256k1<All>,
248✔
2495
    descriptor: E,
248✔
2496
    change_descriptor: E,
248✔
2497
    network: Network,
248✔
2498
) -> Result<(Arc<SignersContainer>, Arc<SignersContainer>), DescriptorError> {
248✔
2499
    let descriptor = into_wallet_descriptor_checked(descriptor, secp, network)?;
248✔
2500
    let change_descriptor = into_wallet_descriptor_checked(change_descriptor, secp, network)?;
248✔
2501
    let (descriptor, keymap) = descriptor;
248✔
2502
    let signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
248✔
2503
    let _ = index
248✔
2504
        .insert_descriptor(KeychainKind::External, descriptor)
248✔
2505
        .expect("this is the first descriptor we're inserting");
248✔
2506

248✔
2507
    let (descriptor, keymap) = change_descriptor;
248✔
2508
    let change_signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
248✔
2509
    let _ = index
248✔
2510
        .insert_descriptor(KeychainKind::Internal, descriptor)
248✔
2511
        .map_err(|e| {
248✔
2512
            use bdk_chain::keychain::InsertDescriptorError;
2✔
2513
            match e {
2✔
2514
                InsertDescriptorError::DescriptorAlreadyAssigned { .. } => {
2515
                    crate::descriptor::error::Error::ExternalAndInternalAreTheSame
2✔
2516
                }
2517
                InsertDescriptorError::KeychainAlreadyAssigned { .. } => {
UNCOV
2518
                    unreachable!("this is the first time we're assigning internal")
×
2519
                }
2520
            }
2521
        })?;
248✔
2522

2523
    Ok((signers, change_signers))
246✔
2524
}
248✔
2525

2526
/// Transforms a [`FeeRate`] to `f64` with unit as sat/vb.
2527
#[macro_export]
2528
#[doc(hidden)]
2529
macro_rules! floating_rate {
2530
    ($rate:expr) => {{
2531
        use $crate::bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
2532
        // sat_kwu / 250.0 -> sat_vb
2533
        $rate.to_sat_per_kwu() as f64 / ((1000 / WITNESS_SCALE_FACTOR) as f64)
2534
    }};
2535
}
2536

2537
#[macro_export]
2538
#[doc(hidden)]
2539
/// Macro for getting a wallet for use in a doctest
2540
macro_rules! doctest_wallet {
2541
    () => {{
2542
        use $crate::bitcoin::{BlockHash, Transaction, absolute, TxOut, Network, hashes::Hash};
2543
        use $crate::chain::{ConfirmationTime, BlockId};
2544
        use $crate::{KeychainKind, wallet::Wallet};
2545
        let descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/0/*)";
2546
        let change_descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/1/*)";
2547

2548
        let mut wallet = Wallet::new(
2549
            descriptor,
2550
            change_descriptor,
2551
            Network::Regtest,
2552
        )
2553
        .unwrap();
2554
        let address = wallet.peek_address(KeychainKind::External, 0).address;
2555
        let tx = Transaction {
2556
            version: transaction::Version::ONE,
2557
            lock_time: absolute::LockTime::ZERO,
2558
            input: vec![],
2559
            output: vec![TxOut {
2560
                value: Amount::from_sat(500_000),
2561
                script_pubkey: address.script_pubkey(),
2562
            }],
2563
        };
2564
        let _ = wallet.insert_checkpoint(BlockId { height: 1_000, hash: BlockHash::all_zeros() });
2565
        let _ = wallet.insert_tx(tx.clone(), ConfirmationTime::Confirmed {
2566
            height: 500,
2567
            time: 50_000
2568
        });
2569

2570
        wallet
2571
    }}
2572
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc