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

bitcoindevkit / bdk / 9519613010

14 Jun 2024 04:52PM UTC coverage: 83.312% (+0.2%) from 83.064%
9519613010

Pull #1473

github

web-flow
Merge feb27df18 into bc420923c
Pull Request #1473: Remove `persist` submodule

58 of 64 new or added lines in 5 files covered. (90.63%)

1 existing line in 1 file now uncovered.

11128 of 13357 relevant lines covered (83.31%)

17626.96 hits per line

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

82.93
/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::ops::Deref;
44
use descriptor::error::Error as DescriptorError;
45
use miniscript::psbt::{PsbtExt, PsbtInputExt, PsbtInputSatisfier};
46

47
use bdk_chain::tx_graph::CalculateFeeError;
48

49
pub mod coin_selection;
50
pub mod export;
51
pub mod signer;
52
pub mod tx_builder;
53
pub(crate) mod utils;
54

55
pub mod error;
56

57
pub use utils::IsDust;
58

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

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

75
use self::coin_selection::Error;
76

77
const COINBASE_MATURITY: u32 = 100;
78

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

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

113
    /// Update for the wallet's internal [`TxGraph`].
114
    pub graph: TxGraph<ConfirmationTimeHeightAnchor>,
115

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

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

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

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

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

157
impl Deref for AddressInfo {
158
    type Target = Address;
159

160
    fn deref(&self) -> &Self::Target {
888✔
161
        &self.address
888✔
162
    }
888✔
163
}
164

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

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

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

191
#[cfg(feature = "std")]
192
impl std::error::Error for NewError {}
193

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

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

224
#[cfg(feature = "std")]
225
impl std::error::Error for LoadError {}
226

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

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

281
#[cfg(feature = "std")]
282
impl std::error::Error for NewOrLoadError {}
283

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

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

310
#[cfg(feature = "std")]
311
impl std::error::Error for InsertTxError {}
312

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

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

343
#[cfg(feature = "std")]
344
impl std::error::Error for ApplyBlockError {}
345

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

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

371
        let (signers, change_signers) =
151✔
372
            create_signers(&mut index, &secp, descriptor, change_descriptor, network)
153✔
373
                .map_err(NewError::Descriptor)?;
153✔
374

375
        let indexed_graph = IndexedTxGraph::new(index);
151✔
376

151✔
377
        let staged = ChangeSet {
151✔
378
            chain: chain_changeset,
151✔
379
            indexed_tx_graph: indexed_graph.initial_changeset(),
151✔
380
            network: Some(network),
151✔
381
        };
151✔
382

151✔
383
        Ok(Wallet {
151✔
384
            signers,
151✔
385
            change_signers,
151✔
386
            network,
151✔
387
            chain,
151✔
388
            indexed_graph,
151✔
389
            stage: staged,
151✔
390
            secp,
151✔
391
        })
151✔
392
    }
153✔
393

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

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

96✔
461
        let mut indexed_graph = IndexedTxGraph::new(index);
96✔
462
        indexed_graph.apply_changeset(changeset.indexed_tx_graph);
96✔
463

96✔
464
        let stage = ChangeSet::default();
96✔
465

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

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

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

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

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

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

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

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

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

1,248✔
647
        AddressInfo {
1,248✔
648
            index,
1,248✔
649
            address: Address::from_script(&spk, self.network).expect("must have address form"),
1,248✔
650
            keychain,
1,248✔
651
        }
1,248✔
652
    }
1,248✔
653

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

120✔
685
        let ((index, spk), index_changeset) = index
120✔
686
            .reveal_next_spk(&keychain)
120✔
687
            .expect("keychain must exist");
120✔
688

120✔
689
        stage.append(indexed_tx_graph::ChangeSet::from(index_changeset).into());
120✔
690

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

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

16✔
719
        self.stage.append(index_changeset.into());
16✔
720

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

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

896✔
739
        let ((index, spk), index_changeset) = index
896✔
740
            .next_unused_spk(&keychain)
896✔
741
            .expect("keychain must exist");
896✔
742

896✔
743
        self.stage
896✔
744
            .append(indexed_tx_graph::ChangeSet::from(index_changeset).into());
896✔
745

896✔
746
        AddressInfo {
896✔
747
            index,
896✔
748
            address: Address::from_script(spk.as_script(), self.network)
896✔
749
                .expect("must have address form"),
896✔
750
            keychain,
896✔
751
        }
896✔
752
    }
896✔
753

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1118
                (Some(anchor), None)
2,230✔
1119
            }
1120
            ConfirmationTime::Unconfirmed { last_seen } => (None, Some(last_seen)),
184✔
1121
        };
1122

1123
        let mut changeset = ChangeSet::default();
2,414✔
1124
        let txid = tx.compute_txid();
2,414✔
1125
        changeset.append(self.indexed_graph.insert_tx(tx).into());
2,414✔
1126
        if let Some(anchor) = anchor {
2,414✔
1127
            changeset.append(self.indexed_graph.insert_anchor(txid, anchor).into());
2,230✔
1128
        }
2,230✔
1129
        if let Some(last_seen) = last_seen {
2,414✔
1130
            changeset.append(self.indexed_graph.insert_seen_at(txid, last_seen).into());
184✔
1131
        }
2,230✔
1132

1133
        let changed = !changeset.is_empty();
2,414✔
1134
        self.stage.append(changeset);
2,414✔
1135
        Ok(changed)
2,414✔
1136
    }
2,414✔
1137

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

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

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

1173
        signers.add_external(signer.id(&self.secp), ordering, signer);
64✔
1174
    }
64✔
1175

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

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

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

1245
        let external_policy = external_descriptor
146✔
1246
            .extract_policy(&self.signers, BuildSatisfaction::None, &self.secp)?
146✔
1247
            .unwrap();
146✔
1248
        let internal_policy = internal_descriptor
146✔
1249
            .extract_policy(&self.change_signers, BuildSatisfaction::None, &self.secp)?
146✔
1250
            .unwrap();
146✔
1251

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

1272
        let external_requirements = external_policy.get_condition(
145✔
1273
            params
145✔
1274
                .external_policy_path
145✔
1275
                .as_ref()
145✔
1276
                .unwrap_or(&BTreeMap::new()),
145✔
1277
        )?;
145✔
1278
        let internal_requirements = internal_policy.get_condition(
145✔
1279
            params
145✔
1280
                .internal_policy_path
145✔
1281
                .as_ref()
145✔
1282
                .unwrap_or(&BTreeMap::new()),
145✔
1283
        )?;
145✔
1284

1285
        let requirements = external_requirements.merge(&internal_requirements)?;
145✔
1286

1287
        let version = match params.version {
143✔
1288
            Some(tx_builder::Version(0)) => return Err(CreateTxError::Version0),
1✔
1289
            Some(tx_builder::Version(1)) if requirements.csv.is_some() => {
18✔
1290
                return Err(CreateTxError::Version1Csv)
1✔
1291
            }
1292
            Some(tx_builder::Version(x)) => x,
18✔
1293
            None if requirements.csv.is_some() => 2,
125✔
1294
            None => 1,
121✔
1295
        };
1296

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

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

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

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

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

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

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

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

1407
        let mut tx = Transaction {
137✔
1408
            version: transaction::Version::non_standard(version),
137✔
1409
            lock_time,
137✔
1410
            input: vec![],
137✔
1411
            output: vec![],
137✔
1412
        };
137✔
1413

137✔
1414
        if params.manually_selected_only && params.utxos.is_empty() {
137✔
1415
            return Err(CreateTxError::NoUtxosSelected);
1✔
1416
        }
136✔
1417

136✔
1418
        let mut outgoing = Amount::ZERO;
136✔
1419
        let mut received = Amount::ZERO;
136✔
1420

136✔
1421
        let recipients = params.recipients.iter().map(|(r, v)| (r, *v));
136✔
1422

1423
        for (index, (script_pubkey, value)) in recipients.enumerate() {
136✔
1424
            if !params.allow_dust && value.is_dust(script_pubkey) && !script_pubkey.is_op_return() {
85✔
1425
                return Err(CreateTxError::OutputBelowDustLimit(index));
1✔
1426
            }
84✔
1427

84✔
1428
            if self.is_mine(script_pubkey) {
84✔
1429
                received += Amount::from_sat(value);
42✔
1430
            }
46✔
1431

1432
            let new_out = TxOut {
84✔
1433
                script_pubkey: script_pubkey.clone(),
84✔
1434
                value: Amount::from_sat(value),
84✔
1435
            };
84✔
1436

84✔
1437
            tx.output.push(new_out);
84✔
1438

84✔
1439
            outgoing += Amount::from_sat(value);
84✔
1440
        }
1441

1442
        fee_amount += (fee_rate * tx.weight()).to_sat();
135✔
1443

135✔
1444
        let (required_utxos, optional_utxos) =
135✔
1445
            self.preselect_utxos(&params, Some(current_height.to_consensus_u32()));
135✔
1446

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

1463
        let (required_utxos, optional_utxos) =
135✔
1464
            coin_selection::filter_duplicates(required_utxos, optional_utxos);
135✔
1465

1466
        let coin_selection = coin_selection.coin_select(
135✔
1467
            required_utxos,
135✔
1468
            optional_utxos,
135✔
1469
            fee_rate,
135✔
1470
            outgoing.to_sat() + fee_amount,
135✔
1471
            &drain_script,
135✔
1472
        )?;
135✔
1473
        fee_amount += coin_selection.fee_amount;
128✔
1474
        let excess = &coin_selection.excess;
128✔
1475

128✔
1476
        tx.input = coin_selection
128✔
1477
            .selected
128✔
1478
            .iter()
128✔
1479
            .map(|u| bitcoin::TxIn {
144✔
1480
                previous_output: u.outpoint(),
144✔
1481
                script_sig: ScriptBuf::default(),
144✔
1482
                sequence: u.sequence().unwrap_or(n_sequence),
144✔
1483
                witness: Witness::new(),
144✔
1484
            })
144✔
1485
            .collect();
128✔
1486

128✔
1487
        if tx.output.is_empty() {
128✔
1488
            // Uh oh, our transaction has no outputs.
1489
            // We allow this when:
1490
            // - We have a drain_to address and the utxos we must spend (this happens,
1491
            // for example, when we RBF)
1492
            // - We have a drain_to address and drain_wallet set
1493
            // Otherwise, we don't know who we should send the funds to, and how much
1494
            // we should send!
1495
            if params.drain_to.is_some() && (params.drain_wallet || !params.utxos.is_empty()) {
51✔
1496
                if let NoChange {
1497
                    dust_threshold,
1✔
1498
                    remaining_amount,
1✔
1499
                    change_fee,
1✔
1500
                } = excess
49✔
1501
                {
1502
                    return Err(CreateTxError::CoinSelection(Error::InsufficientFunds {
1✔
1503
                        needed: *dust_threshold,
1✔
1504
                        available: remaining_amount.saturating_sub(*change_fee),
1✔
1505
                    }));
1✔
1506
                }
48✔
1507
            } else {
1508
                return Err(CreateTxError::NoRecipients);
2✔
1509
            }
1510
        }
77✔
1511

1512
        match excess {
125✔
1513
            NoChange {
1514
                remaining_amount, ..
3✔
1515
            } => fee_amount += remaining_amount,
3✔
1516
            Change { amount, fee } => {
122✔
1517
                if self.is_mine(&drain_script) {
122✔
1518
                    received += Amount::from_sat(*amount);
112✔
1519
                }
112✔
1520
                fee_amount += fee;
122✔
1521

122✔
1522
                // create drain output
122✔
1523
                let drain_output = TxOut {
122✔
1524
                    value: Amount::from_sat(*amount),
122✔
1525
                    script_pubkey: drain_script,
122✔
1526
                };
122✔
1527

122✔
1528
                // TODO: We should pay attention when adding a new output: this might increase
122✔
1529
                // the length of the "number of vouts" parameter by 2 bytes, potentially making
122✔
1530
                // our feerate too low
122✔
1531
                tx.output.push(drain_output);
122✔
1532
            }
1533
        };
1534

1535
        // sort input/outputs according to the chosen algorithm
1536
        params.ordering.sort_tx(&mut tx);
125✔
1537

1538
        let psbt = self.complete_transaction(tx, coin_selection.selected, params)?;
125✔
1539
        Ok(psbt)
123✔
1540
    }
146✔
1541

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

1592
        let mut tx = graph
152✔
1593
            .get_tx(txid)
152✔
1594
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?
152✔
1595
            .as_ref()
152✔
1596
            .clone();
152✔
1597

1598
        let pos = graph
152✔
1599
            .get_chain_position(&self.chain, chain_tip, txid)
152✔
1600
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?;
152✔
1601
        if let ChainPosition::Confirmed(_) = pos {
152✔
1602
            return Err(BuildFeeBumpError::TransactionConfirmed(txid));
8✔
1603
        }
144✔
1604

144✔
1605
        if !tx
144✔
1606
            .input
144✔
1607
            .iter()
144✔
1608
            .any(|txin| txin.sequence.to_consensus_u32() <= 0xFFFFFFFD)
144✔
1609
        {
1610
            return Err(BuildFeeBumpError::IrreplaceableTransaction(
8✔
1611
                tx.compute_txid(),
8✔
1612
            ));
8✔
1613
        }
136✔
1614

1615
        let fee = self
136✔
1616
            .calculate_fee(&tx)
136✔
1617
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1618
        let fee_rate = self
136✔
1619
            .calculate_fee_rate(&tx)
136✔
1620
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1621

1622
        // remove the inputs from the tx and process them
1623
        let original_txin = tx.input.drain(..).collect::<Vec<_>>();
136✔
1624
        let original_utxos = original_txin
136✔
1625
            .iter()
136✔
1626
            .map(|txin| -> Result<_, BuildFeeBumpError> {
144✔
1627
                let prev_tx = graph
144✔
1628
                    .get_tx(txin.previous_output.txid)
144✔
1629
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?;
144✔
1630
                let txout = &prev_tx.output[txin.previous_output.vout as usize];
144✔
1631

1632
                let confirmation_time: ConfirmationTime = graph
144✔
1633
                    .get_chain_position(&self.chain, chain_tip, txin.previous_output.txid)
144✔
1634
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?
144✔
1635
                    .cloned()
144✔
1636
                    .into();
144✔
1637

1638
                let weighted_utxo = match txout_index.index_of_spk(&txout.script_pubkey) {
144✔
1639
                    Some(&(keychain, derivation_index)) => {
144✔
1640
                        let satisfaction_weight = self
144✔
1641
                            .get_descriptor_for_keychain(keychain)
144✔
1642
                            .max_weight_to_satisfy()
144✔
1643
                            .unwrap()
144✔
1644
                            .to_wu() as usize;
144✔
1645
                        WeightedUtxo {
144✔
1646
                            utxo: Utxo::Local(LocalOutput {
144✔
1647
                                outpoint: txin.previous_output,
144✔
1648
                                txout: txout.clone(),
144✔
1649
                                keychain,
144✔
1650
                                is_spent: true,
144✔
1651
                                derivation_index,
144✔
1652
                                confirmation_time,
144✔
1653
                            }),
144✔
1654
                            satisfaction_weight,
144✔
1655
                        }
144✔
1656
                    }
1657
                    None => {
1658
                        let satisfaction_weight =
×
1659
                            serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len();
×
1660
                        WeightedUtxo {
×
1661
                            utxo: Utxo::Foreign {
×
1662
                                outpoint: txin.previous_output,
×
1663
                                sequence: Some(txin.sequence),
×
1664
                                psbt_input: Box::new(psbt::Input {
×
1665
                                    witness_utxo: Some(txout.clone()),
×
1666
                                    non_witness_utxo: Some(prev_tx.as_ref().clone()),
×
1667
                                    ..Default::default()
×
1668
                                }),
×
1669
                            },
×
1670
                            satisfaction_weight,
×
1671
                        }
×
1672
                    }
1673
                };
1674

1675
                Ok(weighted_utxo)
144✔
1676
            })
144✔
1677
            .collect::<Result<Vec<_>, _>>()?;
136✔
1678

1679
        if tx.output.len() > 1 {
136✔
1680
            let mut change_index = None;
80✔
1681
            for (index, txout) in tx.output.iter().enumerate() {
160✔
1682
                let change_keychain = KeychainKind::Internal;
160✔
1683
                match txout_index.index_of_spk(&txout.script_pubkey) {
160✔
1684
                    Some((keychain, _)) if *keychain == change_keychain => {
104✔
1685
                        change_index = Some(index)
80✔
1686
                    }
1687
                    _ => {}
80✔
1688
                }
1689
            }
1690

1691
            if let Some(change_index) = change_index {
80✔
1692
                tx.output.remove(change_index);
80✔
1693
            }
80✔
1694
        }
56✔
1695

1696
        let params = TxParams {
136✔
1697
            // TODO: figure out what rbf option should be?
136✔
1698
            version: Some(tx_builder::Version(tx.version.0)),
136✔
1699
            recipients: tx
136✔
1700
                .output
136✔
1701
                .into_iter()
136✔
1702
                .map(|txout| (txout.script_pubkey, txout.value.to_sat()))
136✔
1703
                .collect(),
136✔
1704
            utxos: original_utxos,
136✔
1705
            bumping_fee: Some(tx_builder::PreviousFee {
136✔
1706
                absolute: fee.to_sat(),
136✔
1707
                rate: fee_rate,
136✔
1708
            }),
136✔
1709
            ..Default::default()
136✔
1710
        };
136✔
1711

136✔
1712
        Ok(TxBuilder {
136✔
1713
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
136✔
1714
            params,
136✔
1715
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
136✔
1716
        })
136✔
1717
    }
152✔
1718

1719
    /// Sign a transaction with all the wallet's signers, in the order specified by every signer's
1720
    /// [`SignerOrdering`]. This function returns the `Result` type with an encapsulated `bool` that has the value true if the PSBT was finalized, or false otherwise.
1721
    ///
1722
    /// The [`SignOptions`] can be used to tweak the behavior of the software signers, and the way
1723
    /// the transaction is finalized at the end. Note that it can't be guaranteed that *every*
1724
    /// signers will follow the options, but the "software signers" (WIF keys and `xprv`) defined
1725
    /// in this library will.
1726
    ///
1727
    /// ## Example
1728
    ///
1729
    /// ```
1730
    /// # use std::str::FromStr;
1731
    /// # use bitcoin::*;
1732
    /// # use bdk_wallet::*;
1733
    /// # use bdk_wallet::wallet::ChangeSet;
1734
    /// # use bdk_wallet::wallet::error::CreateTxError;
1735
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1736
    /// # let mut wallet = doctest_wallet!();
1737
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1738
    /// let mut psbt = {
1739
    ///     let mut builder = wallet.build_tx();
1740
    ///     builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
1741
    ///     builder.finish()?
1742
    /// };
1743
    /// let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
1744
    /// assert!(finalized, "we should have signed all the inputs");
1745
    /// # Ok::<(),anyhow::Error>(())
1746
    pub fn sign(&self, psbt: &mut Psbt, sign_options: SignOptions) -> Result<bool, SignerError> {
344✔
1747
        // This adds all the PSBT metadata for the inputs, which will help us later figure out how
344✔
1748
        // to derive our keys
344✔
1749
        self.update_psbt_with_descriptor(psbt)
344✔
1750
            .map_err(SignerError::MiniscriptPsbt)?;
344✔
1751

1752
        // If we aren't allowed to use `witness_utxo`, ensure that every input (except p2tr and finalized ones)
1753
        // has the `non_witness_utxo`
1754
        if !sign_options.trust_witness_utxo
344✔
1755
            && psbt
296✔
1756
                .inputs
296✔
1757
                .iter()
296✔
1758
                .filter(|i| i.final_script_witness.is_none() && i.final_script_sig.is_none())
304✔
1759
                .filter(|i| i.tap_internal_key.is_none() && i.tap_merkle_root.is_none())
296✔
1760
                .any(|i| i.non_witness_utxo.is_none())
296✔
1761
        {
1762
            return Err(SignerError::MissingNonWitnessUtxo);
×
1763
        }
344✔
1764

344✔
1765
        // If the user hasn't explicitly opted-in, refuse to sign the transaction unless every input
344✔
1766
        // is using `SIGHASH_ALL` or `SIGHASH_DEFAULT` for taproot
344✔
1767
        if !sign_options.allow_all_sighashes
344✔
1768
            && !psbt.inputs.iter().all(|i| {
352✔
1769
                i.sighash_type.is_none()
352✔
1770
                    || i.sighash_type == Some(EcdsaSighashType::All.into())
24✔
1771
                    || i.sighash_type == Some(TapSighashType::All.into())
16✔
1772
                    || i.sighash_type == Some(TapSighashType::Default.into())
16✔
1773
            })
352✔
1774
        {
1775
            return Err(SignerError::NonStandardSighash);
16✔
1776
        }
328✔
1777

1778
        for signer in self
680✔
1779
            .signers
328✔
1780
            .signers()
328✔
1781
            .iter()
328✔
1782
            .chain(self.change_signers.signers().iter())
328✔
1783
        {
1784
            signer.sign_transaction(psbt, &sign_options, &self.secp)?;
680✔
1785
        }
1786

1787
        // attempt to finalize
1788
        if sign_options.try_finalize {
296✔
1789
            self.finalize_psbt(psbt, sign_options)
272✔
1790
        } else {
1791
            Ok(false)
24✔
1792
        }
1793
    }
344✔
1794

1795
    /// Return the spending policies for the wallet's descriptor
1796
    pub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, DescriptorError> {
24✔
1797
        let signers = match keychain {
24✔
1798
            KeychainKind::External => &self.signers,
24✔
1799
            KeychainKind::Internal => &self.change_signers,
×
1800
        };
1801

1802
        self.public_descriptor(keychain).extract_policy(
24✔
1803
            signers,
24✔
1804
            BuildSatisfaction::None,
24✔
1805
            &self.secp,
24✔
1806
        )
24✔
1807
    }
24✔
1808

1809
    /// Return the "public" version of the wallet's descriptor, meaning a new descriptor that has
1810
    /// the same structure but with every secret key removed
1811
    ///
1812
    /// This can be used to build a watch-only version of a wallet
1813
    pub fn public_descriptor(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,268✔
1814
        self.indexed_graph
6,268✔
1815
            .index
6,268✔
1816
            .keychains()
6,268✔
1817
            .find(|(k, _)| *k == &keychain)
7,098✔
1818
            .map(|(_, d)| d)
6,268✔
1819
            .expect("keychain must exist")
6,268✔
1820
    }
6,268✔
1821

1822
    /// Finalize a PSBT, i.e., for each input determine if sufficient data is available to pass
1823
    /// validation and construct the respective `scriptSig` or `scriptWitness`. Please refer to
1824
    /// [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#Input_Finalizer)
1825
    /// for further information.
1826
    ///
1827
    /// Returns `true` if the PSBT could be finalized, and `false` otherwise.
1828
    ///
1829
    /// The [`SignOptions`] can be used to tweak the behavior of the finalizer.
1830
    pub fn finalize_psbt(
272✔
1831
        &self,
272✔
1832
        psbt: &mut Psbt,
272✔
1833
        sign_options: SignOptions,
272✔
1834
    ) -> Result<bool, SignerError> {
272✔
1835
        let chain_tip = self.chain.tip().block_id();
272✔
1836

272✔
1837
        let tx = &psbt.unsigned_tx;
272✔
1838
        let mut finished = true;
272✔
1839

1840
        for (n, input) in tx.input.iter().enumerate() {
312✔
1841
            let psbt_input = &psbt
312✔
1842
                .inputs
312✔
1843
                .get(n)
312✔
1844
                .ok_or(SignerError::InputIndexOutOfRange)?;
312✔
1845
            if psbt_input.final_script_sig.is_some() || psbt_input.final_script_witness.is_some() {
304✔
1846
                continue;
16✔
1847
            }
288✔
1848
            let confirmation_height = self
288✔
1849
                .indexed_graph
288✔
1850
                .graph()
288✔
1851
                .get_chain_position(&self.chain, chain_tip, input.previous_output.txid)
288✔
1852
                .map(|chain_position| match chain_position {
288✔
1853
                    ChainPosition::Confirmed(a) => a.confirmation_height,
264✔
1854
                    ChainPosition::Unconfirmed(_) => u32::MAX,
×
1855
                });
288✔
1856
            let current_height = sign_options
288✔
1857
                .assume_height
288✔
1858
                .unwrap_or_else(|| self.chain.tip().height());
288✔
1859

288✔
1860
            // - Try to derive the descriptor by looking at the txout. If it's in our database, we
288✔
1861
            //   know exactly which `keychain` to use, and which derivation index it is
288✔
1862
            // - If that fails, try to derive it by looking at the psbt input: the complete logic
288✔
1863
            //   is in `src/descriptor/mod.rs`, but it will basically look at `bip32_derivation`,
288✔
1864
            //   `redeem_script` and `witness_script` to determine the right derivation
288✔
1865
            // - If that also fails, it will try it on the internal descriptor, if present
288✔
1866
            let desc = psbt
288✔
1867
                .get_utxo_for(n)
288✔
1868
                .and_then(|txout| self.get_descriptor_for_txout(&txout))
288✔
1869
                .or_else(|| {
288✔
1870
                    self.indexed_graph.index.keychains().find_map(|(_, desc)| {
32✔
1871
                        desc.derive_from_psbt_input(psbt_input, psbt.get_utxo_for(n), &self.secp)
32✔
1872
                    })
32✔
1873
                });
288✔
1874

288✔
1875
            match desc {
288✔
1876
                Some(desc) => {
272✔
1877
                    let mut tmp_input = bitcoin::TxIn::default();
272✔
1878
                    match desc.satisfy(
272✔
1879
                        &mut tmp_input,
272✔
1880
                        (
272✔
1881
                            PsbtInputSatisfier::new(psbt, n),
272✔
1882
                            After::new(Some(current_height), false),
272✔
1883
                            Older::new(Some(current_height), confirmation_height, false),
272✔
1884
                        ),
272✔
1885
                    ) {
272✔
1886
                        Ok(_) => {
1887
                            let psbt_input = &mut psbt.inputs[n];
264✔
1888
                            psbt_input.final_script_sig = Some(tmp_input.script_sig);
264✔
1889
                            psbt_input.final_script_witness = Some(tmp_input.witness);
264✔
1890
                            if sign_options.remove_partial_sigs {
264✔
1891
                                psbt_input.partial_sigs.clear();
240✔
1892
                            }
240✔
1893
                            if sign_options.remove_taproot_extras {
264✔
1894
                                // We just constructed the final witness, clear these fields.
264✔
1895
                                psbt_input.tap_key_sig = None;
264✔
1896
                                psbt_input.tap_script_sigs.clear();
264✔
1897
                                psbt_input.tap_scripts.clear();
264✔
1898
                                psbt_input.tap_key_origins.clear();
264✔
1899
                                psbt_input.tap_internal_key = None;
264✔
1900
                                psbt_input.tap_merkle_root = None;
264✔
1901
                            }
264✔
1902
                        }
1903
                        Err(_) => finished = false,
8✔
1904
                    }
1905
                }
1906
                None => finished = false,
16✔
1907
            }
1908
        }
1909

1910
        if finished && sign_options.remove_taproot_extras {
264✔
1911
            for output in &mut psbt.outputs {
568✔
1912
                output.tap_key_origins.clear();
328✔
1913
            }
328✔
1914
        }
24✔
1915

1916
        Ok(finished)
264✔
1917
    }
272✔
1918

1919
    /// Return the secp256k1 context used for all signing operations
1920
    pub fn secp_ctx(&self) -> &SecpCtx {
28✔
1921
        &self.secp
28✔
1922
    }
28✔
1923

1924
    /// Returns the descriptor used to create addresses for a particular `keychain`.
1925
    pub fn get_descriptor_for_keychain(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,100✔
1926
        self.public_descriptor(keychain)
6,100✔
1927
    }
6,100✔
1928

1929
    /// The derivation index of this wallet. It will return `None` if it has not derived any addresses.
1930
    /// Otherwise, it will return the index of the highest address it has derived.
1931
    pub fn derivation_index(&self, keychain: KeychainKind) -> Option<u32> {
40✔
1932
        self.indexed_graph.index.last_revealed_index(&keychain)
40✔
1933
    }
40✔
1934

1935
    /// The index of the next address that you would get if you were to ask the wallet for a new address
1936
    pub fn next_derivation_index(&self, keychain: KeychainKind) -> u32 {
×
1937
        self.indexed_graph
×
1938
            .index
×
1939
            .next_index(&keychain)
×
1940
            .expect("keychain must exist")
×
1941
            .0
×
1942
    }
×
1943

1944
    /// Informs the wallet that you no longer intend to broadcast a tx that was built from it.
1945
    ///
1946
    /// This frees up the change address used when creating the tx for use in future transactions.
1947
    // TODO: Make this free up reserved utxos when that's implemented
1948
    pub fn cancel_tx(&mut self, tx: &Transaction) {
16✔
1949
        let txout_index = &mut self.indexed_graph.index;
16✔
1950
        for txout in &tx.output {
48✔
1951
            if let Some((keychain, index)) = txout_index.index_of_spk(&txout.script_pubkey) {
32✔
1952
                // NOTE: unmark_used will **not** make something unused if it has actually been used
16✔
1953
                // by a tx in the tracker. It only removes the superficial marking.
16✔
1954
                txout_index.unmark_used(*keychain, *index);
16✔
1955
            }
16✔
1956
        }
1957
    }
16✔
1958

1959
    fn get_descriptor_for_txout(&self, txout: &TxOut) -> Option<DerivedDescriptor> {
288✔
1960
        let &(keychain, child) = self
288✔
1961
            .indexed_graph
288✔
1962
            .index
288✔
1963
            .index_of_spk(&txout.script_pubkey)?;
288✔
1964
        let descriptor = self.get_descriptor_for_keychain(keychain);
272✔
1965
        descriptor.at_derivation_index(child).ok()
272✔
1966
    }
288✔
1967

1968
    fn get_available_utxos(&self) -> Vec<(LocalOutput, usize)> {
1,136✔
1969
        self.list_unspent()
1,136✔
1970
            .map(|utxo| {
1,248✔
1971
                let keychain = utxo.keychain;
1,248✔
1972
                (utxo, {
1,248✔
1973
                    self.get_descriptor_for_keychain(keychain)
1,248✔
1974
                        .max_weight_to_satisfy()
1,248✔
1975
                        .unwrap()
1,248✔
1976
                        .to_wu() as usize
1,248✔
1977
                })
1,248✔
1978
            })
1,248✔
1979
            .collect()
1,136✔
1980
    }
1,136✔
1981

1982
    /// Given the options returns the list of utxos that must be used to form the
1983
    /// transaction and any further that may be used if needed.
1984
    fn preselect_utxos(
1,136✔
1985
        &self,
1,136✔
1986
        params: &TxParams,
1,136✔
1987
        current_height: Option<u32>,
1,136✔
1988
    ) -> (Vec<WeightedUtxo>, Vec<WeightedUtxo>) {
1,136✔
1989
        let TxParams {
1,136✔
1990
            change_policy,
1,136✔
1991
            unspendable,
1,136✔
1992
            utxos,
1,136✔
1993
            drain_wallet,
1,136✔
1994
            manually_selected_only,
1,136✔
1995
            bumping_fee,
1,136✔
1996
            ..
1,136✔
1997
        } = params;
1,136✔
1998

1,136✔
1999
        let manually_selected = utxos.clone();
1,136✔
2000
        // we mandate confirmed transactions if we're bumping the fee
1,136✔
2001
        let must_only_use_confirmed_tx = bumping_fee.is_some();
1,136✔
2002
        let must_use_all_available = *drain_wallet;
1,136✔
2003

1,136✔
2004
        let chain_tip = self.chain.tip().block_id();
1,136✔
2005
        //    must_spend <- manually selected utxos
1,136✔
2006
        //    may_spend  <- all other available utxos
1,136✔
2007
        let mut may_spend = self.get_available_utxos();
1,136✔
2008

1,136✔
2009
        may_spend.retain(|may_spend| {
1,248✔
2010
            !manually_selected
1,248✔
2011
                .iter()
1,248✔
2012
                .any(|manually_selected| manually_selected.utxo.outpoint() == may_spend.0.outpoint)
1,248✔
2013
        });
1,248✔
2014
        let mut must_spend = manually_selected;
1,136✔
2015

1,136✔
2016
        // NOTE: we are intentionally ignoring `unspendable` here. i.e manual
1,136✔
2017
        // selection overrides unspendable.
1,136✔
2018
        if *manually_selected_only {
1,136✔
2019
            return (must_spend, vec![]);
40✔
2020
        }
1,096✔
2021

1,096✔
2022
        let satisfies_confirmed = may_spend
1,096✔
2023
            .iter()
1,096✔
2024
            .map(|u| -> bool {
1,136✔
2025
                let txid = u.0.outpoint.txid;
1,136✔
2026
                let tx = match self.indexed_graph.graph().get_tx(txid) {
1,136✔
2027
                    Some(tx) => tx,
1,136✔
2028
                    None => return false,
×
2029
                };
2030
                let confirmation_time: ConfirmationTime = match self
1,136✔
2031
                    .indexed_graph
1,136✔
2032
                    .graph()
1,136✔
2033
                    .get_chain_position(&self.chain, chain_tip, txid)
1,136✔
2034
                {
2035
                    Some(chain_position) => chain_position.cloned().into(),
1,136✔
2036
                    None => return false,
×
2037
                };
2038

2039
                // Whether the UTXO is mature and, if needed, confirmed
2040
                let mut spendable = true;
1,136✔
2041
                if must_only_use_confirmed_tx && !confirmation_time.is_confirmed() {
1,136✔
2042
                    return false;
64✔
2043
                }
1,072✔
2044
                if tx.is_coinbase() {
1,072✔
2045
                    debug_assert!(
24✔
2046
                        confirmation_time.is_confirmed(),
24✔
2047
                        "coinbase must always be confirmed"
×
2048
                    );
2049
                    if let Some(current_height) = current_height {
24✔
2050
                        match confirmation_time {
24✔
2051
                            ConfirmationTime::Confirmed { height, .. } => {
24✔
2052
                                // https://github.com/bitcoin/bitcoin/blob/c5e67be03bb06a5d7885c55db1f016fbf2333fe3/src/validation.cpp#L373-L375
24✔
2053
                                spendable &=
24✔
2054
                                    (current_height.saturating_sub(height)) >= COINBASE_MATURITY;
24✔
2055
                            }
24✔
2056
                            ConfirmationTime::Unconfirmed { .. } => spendable = false,
×
2057
                        }
2058
                    }
×
2059
                }
1,048✔
2060
                spendable
1,072✔
2061
            })
1,136✔
2062
            .collect::<Vec<_>>();
1,096✔
2063

1,096✔
2064
        let mut i = 0;
1,096✔
2065
        may_spend.retain(|u| {
1,136✔
2066
            let retain = change_policy.is_satisfied_by(&u.0)
1,136✔
2067
                && !unspendable.contains(&u.0.outpoint)
1,128✔
2068
                && satisfies_confirmed[i];
1,128✔
2069
            i += 1;
1,136✔
2070
            retain
1,136✔
2071
        });
1,136✔
2072

1,096✔
2073
        let mut may_spend = may_spend
1,096✔
2074
            .into_iter()
1,096✔
2075
            .map(|(local_utxo, satisfaction_weight)| WeightedUtxo {
1,096✔
2076
                satisfaction_weight,
1,048✔
2077
                utxo: Utxo::Local(local_utxo),
1,048✔
2078
            })
1,096✔
2079
            .collect();
1,096✔
2080

1,096✔
2081
        if must_use_all_available {
1,096✔
2082
            must_spend.append(&mut may_spend);
400✔
2083
        }
696✔
2084

2085
        (must_spend, may_spend)
1,096✔
2086
    }
1,136✔
2087

2088
    fn complete_transaction(
1,056✔
2089
        &self,
1,056✔
2090
        tx: Transaction,
1,056✔
2091
        selected: Vec<Utxo>,
1,056✔
2092
        params: TxParams,
1,056✔
2093
    ) -> Result<Psbt, CreateTxError> {
1,056✔
2094
        let mut psbt = Psbt::from_unsigned_tx(tx)?;
1,056✔
2095

2096
        if params.add_global_xpubs {
1,056✔
2097
            let all_xpubs = self
24✔
2098
                .keychains()
24✔
2099
                .flat_map(|(_, desc)| desc.get_extended_keys())
48✔
2100
                .collect::<Vec<_>>();
24✔
2101

2102
            for xpub in all_xpubs {
56✔
2103
                let origin = match xpub.origin {
32✔
2104
                    Some(origin) => origin,
24✔
2105
                    None if xpub.xkey.depth == 0 => {
16✔
2106
                        (xpub.root_fingerprint(&self.secp), vec![].into())
8✔
2107
                    }
2108
                    _ => return Err(CreateTxError::MissingKeyOrigin(xpub.xkey.to_string())),
8✔
2109
                };
2110

2111
                psbt.xpub.insert(xpub.xkey, origin);
32✔
2112
            }
2113
        }
1,032✔
2114

2115
        let mut lookup_output = selected
1,048✔
2116
            .into_iter()
1,048✔
2117
            .map(|utxo| (utxo.outpoint(), utxo))
1,176✔
2118
            .collect::<HashMap<_, _>>();
1,048✔
2119

2120
        // add metadata for the inputs
2121
        for (psbt_input, input) in psbt.inputs.iter_mut().zip(psbt.unsigned_tx.input.iter()) {
1,176✔
2122
            let utxo = match lookup_output.remove(&input.previous_output) {
1,176✔
2123
                Some(utxo) => utxo,
1,176✔
2124
                None => continue,
×
2125
            };
2126

2127
            match utxo {
1,176✔
2128
                Utxo::Local(utxo) => {
1,128✔
2129
                    *psbt_input =
1,128✔
2130
                        match self.get_psbt_input(utxo, params.sighash, params.only_witness_utxo) {
1,128✔
2131
                            Ok(psbt_input) => psbt_input,
1,128✔
2132
                            Err(e) => match e {
×
2133
                                CreateTxError::UnknownUtxo => psbt::Input {
×
2134
                                    sighash_type: params.sighash,
×
2135
                                    ..psbt::Input::default()
×
2136
                                },
×
2137
                                _ => return Err(e),
×
2138
                            },
2139
                        }
2140
                }
2141
                Utxo::Foreign {
2142
                    outpoint,
48✔
2143
                    psbt_input: foreign_psbt_input,
48✔
2144
                    ..
48✔
2145
                } => {
48✔
2146
                    let is_taproot = foreign_psbt_input
48✔
2147
                        .witness_utxo
48✔
2148
                        .as_ref()
48✔
2149
                        .map(|txout| txout.script_pubkey.is_p2tr())
48✔
2150
                        .unwrap_or(false);
48✔
2151
                    if !is_taproot
48✔
2152
                        && !params.only_witness_utxo
40✔
2153
                        && foreign_psbt_input.non_witness_utxo.is_none()
16✔
2154
                    {
2155
                        return Err(CreateTxError::MissingNonWitnessUtxo(outpoint));
8✔
2156
                    }
40✔
2157
                    *psbt_input = *foreign_psbt_input;
40✔
2158
                }
2159
            }
2160
        }
2161

2162
        self.update_psbt_with_descriptor(&mut psbt)?;
1,040✔
2163

2164
        Ok(psbt)
1,040✔
2165
    }
1,056✔
2166

2167
    /// get the corresponding PSBT Input for a LocalUtxo
2168
    pub fn get_psbt_input(
1,144✔
2169
        &self,
1,144✔
2170
        utxo: LocalOutput,
1,144✔
2171
        sighash_type: Option<psbt::PsbtSighashType>,
1,144✔
2172
        only_witness_utxo: bool,
1,144✔
2173
    ) -> Result<psbt::Input, CreateTxError> {
1,144✔
2174
        // Try to find the prev_script in our db to figure out if this is internal or external,
2175
        // and the derivation index
2176
        let &(keychain, child) = self
1,144✔
2177
            .indexed_graph
1,144✔
2178
            .index
1,144✔
2179
            .index_of_spk(&utxo.txout.script_pubkey)
1,144✔
2180
            .ok_or(CreateTxError::UnknownUtxo)?;
1,144✔
2181

2182
        let mut psbt_input = psbt::Input {
1,144✔
2183
            sighash_type,
1,144✔
2184
            ..psbt::Input::default()
1,144✔
2185
        };
1,144✔
2186

1,144✔
2187
        let desc = self.get_descriptor_for_keychain(keychain);
1,144✔
2188
        let derived_descriptor = desc
1,144✔
2189
            .at_derivation_index(child)
1,144✔
2190
            .expect("child can't be hardened");
1,144✔
2191

1,144✔
2192
        psbt_input
1,144✔
2193
            .update_with_descriptor_unchecked(&derived_descriptor)
1,144✔
2194
            .map_err(MiniscriptPsbtError::Conversion)?;
1,144✔
2195

2196
        let prev_output = utxo.outpoint;
1,144✔
2197
        if let Some(prev_tx) = self.indexed_graph.graph().get_tx(prev_output.txid) {
1,144✔
2198
            if desc.is_witness() || desc.is_taproot() {
1,144✔
2199
                psbt_input.witness_utxo = Some(prev_tx.output[prev_output.vout as usize].clone());
1,112✔
2200
            }
1,112✔
2201
            if !desc.is_taproot() && (!desc.is_witness() || !only_witness_utxo) {
1,144✔
2202
                psbt_input.non_witness_utxo = Some(prev_tx.as_ref().clone());
912✔
2203
            }
912✔
2204
        }
×
2205
        Ok(psbt_input)
1,144✔
2206
    }
1,144✔
2207

2208
    fn update_psbt_with_descriptor(&self, psbt: &mut Psbt) -> Result<(), MiniscriptPsbtError> {
1,384✔
2209
        // We need to borrow `psbt` mutably within the loops, so we have to allocate a vec for all
1,384✔
2210
        // the input utxos and outputs
1,384✔
2211
        let utxos = (0..psbt.inputs.len())
1,384✔
2212
            .filter_map(|i| psbt.get_utxo_for(i).map(|utxo| (true, i, utxo)))
1,552✔
2213
            .chain(
1,384✔
2214
                psbt.unsigned_tx
1,384✔
2215
                    .output
1,384✔
2216
                    .iter()
1,384✔
2217
                    .enumerate()
1,384✔
2218
                    .map(|(i, out)| (false, i, out.clone())),
2,184✔
2219
            )
1,384✔
2220
            .collect::<Vec<_>>();
1,384✔
2221

2222
        // Try to figure out the keychain and derivation for every input and output
2223
        for (is_input, index, out) in utxos.into_iter() {
3,696✔
2224
            if let Some(&(keychain, child)) =
3,120✔
2225
                self.indexed_graph.index.index_of_spk(&out.script_pubkey)
3,696✔
2226
            {
2227
                let desc = self.get_descriptor_for_keychain(keychain);
3,120✔
2228
                let desc = desc
3,120✔
2229
                    .at_derivation_index(child)
3,120✔
2230
                    .expect("child can't be hardened");
3,120✔
2231

3,120✔
2232
                if is_input {
3,120✔
2233
                    psbt.update_input_with_descriptor(index, &desc)
1,440✔
2234
                        .map_err(MiniscriptPsbtError::UtxoUpdate)?;
1,440✔
2235
                } else {
2236
                    psbt.update_output_with_descriptor(index, &desc)
1,680✔
2237
                        .map_err(MiniscriptPsbtError::OutputUpdate)?;
1,680✔
2238
                }
2239
            }
576✔
2240
        }
2241

2242
        Ok(())
1,384✔
2243
    }
1,384✔
2244

2245
    /// Return the checksum of the public descriptor associated to `keychain`
2246
    ///
2247
    /// Internally calls [`Self::get_descriptor_for_keychain`] to fetch the right descriptor
2248
    pub fn descriptor_checksum(&self, keychain: KeychainKind) -> String {
8✔
2249
        self.get_descriptor_for_keychain(keychain)
8✔
2250
            .to_string()
8✔
2251
            .split_once('#')
8✔
2252
            .unwrap()
8✔
2253
            .1
8✔
2254
            .to_string()
8✔
2255
    }
8✔
2256

2257
    /// Applies an update to the wallet and stages the changes (but does not persist them).
2258
    ///
2259
    /// Usually you create an `update` by interacting with some blockchain data source and inserting
2260
    /// transactions related to your wallet into it.
2261
    ///
2262
    /// After applying updates you should persist the staged wallet changes. For an example of how
2263
    /// to persist staged wallet changes see [`Wallet::reveal_next_address`]. `
2264
    ///
2265
    /// [`commit`]: Self::commit
2266
    pub fn apply_update(&mut self, update: impl Into<Update>) -> Result<(), CannotConnectError> {
×
2267
        let update = update.into();
×
2268
        let mut changeset = match update.chain {
×
2269
            Some(chain_update) => ChangeSet::from(self.chain.apply_update(chain_update)?),
×
2270
            None => ChangeSet::default(),
×
2271
        };
2272

2273
        let index_changeset = self
×
2274
            .indexed_graph
×
2275
            .index
×
2276
            .reveal_to_target_multi(&update.last_active_indices);
×
2277
        changeset.append(index_changeset.into());
×
2278
        changeset.append(self.indexed_graph.apply_update(update.graph).into());
×
2279
        self.stage.append(changeset);
×
2280
        Ok(())
×
2281
    }
×
2282

2283
    /// Get a reference of the staged [`ChangeSet`] that are yet to be committed (if any).
NEW
2284
    pub fn staged(&self) -> Option<&ChangeSet> {
×
NEW
2285
        if self.stage.is_empty() {
×
NEW
2286
            None
×
2287
        } else {
NEW
2288
            Some(&self.stage)
×
2289
        }
UNCOV
2290
    }
×
2291

2292
    /// Take the staged [`ChangeSet`] to be persisted now (if any).
2293
    pub fn take_staged(&mut self) -> Option<ChangeSet> {
32✔
2294
        self.stage.take()
32✔
2295
    }
32✔
2296

2297
    /// Get a reference to the inner [`TxGraph`].
2298
    pub fn tx_graph(&self) -> &TxGraph<ConfirmationTimeHeightAnchor> {
×
2299
        self.indexed_graph.graph()
×
2300
    }
×
2301

2302
    /// Get a reference to the inner [`KeychainTxOutIndex`].
2303
    pub fn spk_index(&self) -> &KeychainTxOutIndex<KeychainKind> {
48✔
2304
        &self.indexed_graph.index
48✔
2305
    }
48✔
2306

2307
    /// Get a reference to the inner [`LocalChain`].
2308
    pub fn local_chain(&self) -> &LocalChain {
×
2309
        &self.chain
×
2310
    }
×
2311

2312
    /// Introduces a `block` of `height` to the wallet, and tries to connect it to the
2313
    /// `prev_blockhash` of the block's header.
2314
    ///
2315
    /// This is a convenience method that is equivalent to calling [`apply_block_connected_to`]
2316
    /// with `prev_blockhash` and `height-1` as the `connected_to` parameter.
2317
    ///
2318
    /// [`apply_block_connected_to`]: Self::apply_block_connected_to
2319
    pub fn apply_block(&mut self, block: &Block, height: u32) -> Result<(), CannotConnectError> {
×
2320
        let connected_to = match height.checked_sub(1) {
×
2321
            Some(prev_height) => BlockId {
×
2322
                height: prev_height,
×
2323
                hash: block.header.prev_blockhash,
×
2324
            },
×
2325
            None => BlockId {
×
2326
                height,
×
2327
                hash: block.block_hash(),
×
2328
            },
×
2329
        };
2330
        self.apply_block_connected_to(block, height, connected_to)
×
2331
            .map_err(|err| match err {
×
2332
                ApplyHeaderError::InconsistentBlocks => {
2333
                    unreachable!("connected_to is derived from the block so must be consistent")
×
2334
                }
2335
                ApplyHeaderError::CannotConnect(err) => err,
×
2336
            })
×
2337
    }
×
2338

2339
    /// Applies relevant transactions from `block` of `height` to the wallet, and connects the
2340
    /// block to the internal chain.
2341
    ///
2342
    /// The `connected_to` parameter informs the wallet how this block connects to the internal
2343
    /// [`LocalChain`]. Relevant transactions are filtered from the `block` and inserted into the
2344
    /// internal [`TxGraph`].
2345
    ///
2346
    /// **WARNING**: You must persist the changes resulting from one or more calls to this method
2347
    /// if you need the inserted block data to be reloaded after closing the wallet.
2348
    /// See [`Wallet::reveal_next_address`].
2349
    pub fn apply_block_connected_to(
×
2350
        &mut self,
×
2351
        block: &Block,
×
2352
        height: u32,
×
2353
        connected_to: BlockId,
×
2354
    ) -> Result<(), ApplyHeaderError> {
×
2355
        let mut changeset = ChangeSet::default();
×
2356
        changeset.append(
×
2357
            self.chain
×
2358
                .apply_header_connected_to(&block.header, height, connected_to)?
×
2359
                .into(),
×
2360
        );
×
2361
        changeset.append(
×
2362
            self.indexed_graph
×
2363
                .apply_block_relevant(block, height)
×
2364
                .into(),
×
2365
        );
×
2366
        self.stage.append(changeset);
×
2367
        Ok(())
×
2368
    }
×
2369

2370
    /// Apply relevant unconfirmed transactions to the wallet.
2371
    ///
2372
    /// Transactions that are not relevant are filtered out.
2373
    ///
2374
    /// This method takes in an iterator of `(tx, last_seen)` where `last_seen` is the timestamp of
2375
    /// when the transaction was last seen in the mempool. This is used for conflict resolution
2376
    /// when there is conflicting unconfirmed transactions. The transaction with the later
2377
    /// `last_seen` is prioritized.
2378
    ///
2379
    /// **WARNING**: You must persist the changes resulting from one or more calls to this method
2380
    /// if you need the applied unconfirmed transactions to be reloaded after closing the wallet.
2381
    /// See [`Wallet::reveal_next_address`].
2382
    pub fn apply_unconfirmed_txs<'t>(
×
2383
        &mut self,
×
2384
        unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>,
×
2385
    ) {
×
2386
        let indexed_graph_changeset = self
×
2387
            .indexed_graph
×
2388
            .batch_insert_relevant_unconfirmed(unconfirmed_txs);
×
2389
        self.stage.append(indexed_graph_changeset.into());
×
2390
    }
×
2391
}
2392

2393
/// Methods to construct sync/full-scan requests for spk-based chain sources.
2394
impl Wallet {
2395
    /// Create a partial [`SyncRequest`] for this wallet for all revealed spks.
2396
    ///
2397
    /// This is the first step when performing a spk-based wallet partial sync, the returned
2398
    /// [`SyncRequest`] collects all revealed script pubkeys from the wallet keychain needed to
2399
    /// start a blockchain sync with a spk based blockchain client.
2400
    pub fn start_sync_with_revealed_spks(&self) -> SyncRequest {
×
2401
        SyncRequest::from_chain_tip(self.chain.tip())
×
2402
            .populate_with_revealed_spks(&self.indexed_graph.index, ..)
×
2403
    }
×
2404

2405
    /// Create a [`FullScanRequest] for this wallet.
2406
    ///
2407
    /// This is the first step when performing a spk-based wallet full scan, the returned
2408
    /// [`FullScanRequest] collects iterators for the wallet's keychain script pub keys needed to
2409
    /// start a blockchain full scan with a spk based blockchain client.
2410
    ///
2411
    /// This operation is generally only used when importing or restoring a previously used wallet
2412
    /// in which the list of used scripts is not known.
2413
    pub fn start_full_scan(&self) -> FullScanRequest<KeychainKind> {
×
2414
        FullScanRequest::from_keychain_txout_index(self.chain.tip(), &self.indexed_graph.index)
×
2415
    }
×
2416
}
2417

2418
impl AsRef<bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor>> for Wallet {
2419
    fn as_ref(&self) -> &bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor> {
×
2420
        self.indexed_graph.graph()
×
2421
    }
×
2422
}
2423

2424
/// Deterministically generate a unique name given the descriptors defining the wallet
2425
///
2426
/// Compatible with [`wallet_name_from_descriptor`]
2427
pub fn wallet_name_from_descriptor<T>(
×
2428
    descriptor: T,
×
2429
    change_descriptor: Option<T>,
×
2430
    network: Network,
×
2431
    secp: &SecpCtx,
×
2432
) -> Result<String, DescriptorError>
×
2433
where
×
2434
    T: IntoWalletDescriptor,
×
2435
{
×
2436
    //TODO check descriptors contains only public keys
2437
    let descriptor = descriptor
×
2438
        .into_wallet_descriptor(secp, network)?
×
2439
        .0
2440
        .to_string();
×
2441
    let mut wallet_name = calc_checksum(&descriptor[..descriptor.find('#').unwrap()])?;
×
2442
    if let Some(change_descriptor) = change_descriptor {
×
2443
        let change_descriptor = change_descriptor
×
2444
            .into_wallet_descriptor(secp, network)?
×
2445
            .0
2446
            .to_string();
×
2447
        wallet_name.push_str(
×
2448
            calc_checksum(&change_descriptor[..change_descriptor.find('#').unwrap()])?.as_str(),
×
2449
        );
2450
    }
×
2451

2452
    Ok(wallet_name)
×
2453
}
×
2454

2455
fn new_local_utxo(
1,400✔
2456
    keychain: KeychainKind,
1,400✔
2457
    derivation_index: u32,
1,400✔
2458
    full_txo: FullTxOut<ConfirmationTimeHeightAnchor>,
1,400✔
2459
) -> LocalOutput {
1,400✔
2460
    LocalOutput {
1,400✔
2461
        outpoint: full_txo.outpoint,
1,400✔
2462
        txout: full_txo.txout,
1,400✔
2463
        is_spent: full_txo.spent_by.is_some(),
1,400✔
2464
        confirmation_time: full_txo.chain_position.into(),
1,400✔
2465
        keychain,
1,400✔
2466
        derivation_index,
1,400✔
2467
    }
1,400✔
2468
}
1,400✔
2469

2470
fn create_signers<E: IntoWalletDescriptor>(
249✔
2471
    index: &mut KeychainTxOutIndex<KeychainKind>,
249✔
2472
    secp: &Secp256k1<All>,
249✔
2473
    descriptor: E,
249✔
2474
    change_descriptor: E,
249✔
2475
    network: Network,
249✔
2476
) -> Result<(Arc<SignersContainer>, Arc<SignersContainer>), DescriptorError> {
249✔
2477
    let descriptor = into_wallet_descriptor_checked(descriptor, secp, network)?;
249✔
2478
    let change_descriptor = into_wallet_descriptor_checked(change_descriptor, secp, network)?;
249✔
2479
    let (descriptor, keymap) = descriptor;
249✔
2480
    let signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
249✔
2481
    let _ = index
249✔
2482
        .insert_descriptor(KeychainKind::External, descriptor)
249✔
2483
        .expect("this is the first descriptor we're inserting");
249✔
2484

249✔
2485
    let (descriptor, keymap) = change_descriptor;
249✔
2486
    let change_signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
249✔
2487
    let _ = index
249✔
2488
        .insert_descriptor(KeychainKind::Internal, descriptor)
249✔
2489
        .map_err(|e| {
249✔
2490
            use bdk_chain::keychain::InsertDescriptorError;
2✔
2491
            match e {
2✔
2492
                InsertDescriptorError::DescriptorAlreadyAssigned { .. } => {
2493
                    crate::descriptor::error::Error::ExternalAndInternalAreTheSame
2✔
2494
                }
2495
                InsertDescriptorError::KeychainAlreadyAssigned { .. } => {
2496
                    unreachable!("this is the first time we're assigning internal")
×
2497
                }
2498
            }
2499
        })?;
249✔
2500

2501
    Ok((signers, change_signers))
247✔
2502
}
249✔
2503

2504
/// Transforms a [`FeeRate`] to `f64` with unit as sat/vb.
2505
#[macro_export]
2506
#[doc(hidden)]
2507
macro_rules! floating_rate {
2508
    ($rate:expr) => {{
2509
        use $crate::bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
2510
        // sat_kwu / 250.0 -> sat_vb
2511
        $rate.to_sat_per_kwu() as f64 / ((1000 / WITNESS_SCALE_FACTOR) as f64)
2512
    }};
2513
}
2514

2515
#[macro_export]
2516
#[doc(hidden)]
2517
/// Macro for getting a wallet for use in a doctest
2518
macro_rules! doctest_wallet {
2519
    () => {{
2520
        use $crate::bitcoin::{BlockHash, Transaction, absolute, TxOut, Network, hashes::Hash};
2521
        use $crate::chain::{ConfirmationTime, BlockId};
2522
        use $crate::{KeychainKind, wallet::Wallet};
2523
        let descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/0/*)";
2524
        let change_descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/1/*)";
2525

2526
        let mut wallet = Wallet::new(
2527
            descriptor,
2528
            change_descriptor,
2529
            Network::Regtest,
2530
        )
2531
        .unwrap();
2532
        let address = wallet.peek_address(KeychainKind::External, 0).address;
2533
        let tx = Transaction {
2534
            version: transaction::Version::ONE,
2535
            lock_time: absolute::LockTime::ZERO,
2536
            input: vec![],
2537
            output: vec![TxOut {
2538
                value: Amount::from_sat(500_000),
2539
                script_pubkey: address.script_pubkey(),
2540
            }],
2541
        };
2542
        let _ = wallet.insert_checkpoint(BlockId { height: 1_000, hash: BlockHash::all_zeros() });
2543
        let _ = wallet.insert_tx(tx.clone(), ConfirmationTime::Confirmed {
2544
            height: 500,
2545
            time: 50_000
2546
        });
2547

2548
        wallet
2549
    }}
2550
}
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