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

bitcoindevkit / bdk / 9622580725

22 Jun 2024 03:32AM UTC coverage: 83.295% (-0.01%) from 83.305%
9622580725

Pull #1468

github

web-flow
Merge d8c609b6d into e406675f4
Pull Request #1468: feat: use `Weight` type instead of `usize`

17 of 20 new or added lines in 3 files covered. (85.0%)

2 existing lines in 1 file now uncovered.

11119 of 13349 relevant lines covered (83.29%)

17393.66 hits per line

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

82.8
/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::sighash::{EcdsaSighashType, TapSighashType};
35
use bitcoin::{
36
    absolute, psbt, Address, Block, FeeRate, Network, OutPoint, Script, ScriptBuf, Sequence,
37
    Transaction, TxOut, Txid, Witness,
38
};
39
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
40
use bitcoin::{constants::genesis_block, Amount};
41
use bitcoin::{
42
    secp256k1::{All, Secp256k1},
43
    Weight,
44
};
45
use core::fmt;
46
use core::mem;
47
use core::ops::Deref;
48
use descriptor::error::Error as DescriptorError;
49
use miniscript::psbt::{PsbtExt, PsbtInputExt, PsbtInputSatisfier};
50

51
use bdk_chain::tx_graph::CalculateFeeError;
52

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

59
pub mod error;
60

61
pub use utils::IsDust;
62

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

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

79
use self::coin_selection::Error;
80

81
const COINBASE_MATURITY: u32 = 100;
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1470
        let coin_selection = coin_selection.coin_select(
134✔
1471
            required_utxos,
134✔
1472
            optional_utxos,
134✔
1473
            fee_rate,
134✔
1474
            outgoing.to_sat() + fee_amount,
134✔
1475
            &drain_script,
134✔
1476
        )?;
134✔
1477
        fee_amount += coin_selection.fee_amount;
127✔
1478
        let excess = &coin_selection.excess;
127✔
1479

127✔
1480
        tx.input = coin_selection
127✔
1481
            .selected
127✔
1482
            .iter()
127✔
1483
            .map(|u| bitcoin::TxIn {
143✔
1484
                previous_output: u.outpoint(),
143✔
1485
                script_sig: ScriptBuf::default(),
143✔
1486
                sequence: u.sequence().unwrap_or(n_sequence),
143✔
1487
                witness: Witness::new(),
143✔
1488
            })
143✔
1489
            .collect();
127✔
1490

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

1516
        match excess {
124✔
1517
            NoChange {
1518
                remaining_amount, ..
3✔
1519
            } => fee_amount += remaining_amount,
3✔
1520
            Change { amount, fee } => {
121✔
1521
                if self.is_mine(&drain_script) {
121✔
1522
                    received += Amount::from_sat(*amount);
111✔
1523
                }
111✔
1524
                fee_amount += fee;
121✔
1525

121✔
1526
                // create drain output
121✔
1527
                let drain_output = TxOut {
121✔
1528
                    value: Amount::from_sat(*amount),
121✔
1529
                    script_pubkey: drain_script,
121✔
1530
                };
121✔
1531

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

1539
        // sort input/outputs according to the chosen algorithm
1540
        params.ordering.sort_tx(&mut tx);
124✔
1541

1542
        let psbt = self.complete_transaction(tx, coin_selection.selected, params)?;
124✔
1543
        Ok(psbt)
122✔
1544
    }
145✔
1545

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

1596
        let mut tx = graph
152✔
1597
            .get_tx(txid)
152✔
1598
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?
152✔
1599
            .as_ref()
152✔
1600
            .clone();
152✔
1601

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

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

1619
        let fee = self
136✔
1620
            .calculate_fee(&tx)
136✔
1621
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1622
        let fee_rate = self
136✔
1623
            .calculate_fee_rate(&tx)
136✔
1624
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1625

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

1636
                let confirmation_time: ConfirmationTime = graph
144✔
1637
                    .get_chain_position(&self.chain, chain_tip, txin.previous_output.txid)
144✔
1638
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?
144✔
1639
                    .cloned()
144✔
1640
                    .into();
144✔
1641

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

1679
                Ok(weighted_utxo)
144✔
1680
            })
144✔
1681
            .collect::<Result<Vec<_>, _>>()?;
136✔
1682

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

1695
            if let Some(change_index) = change_index {
80✔
1696
                tx.output.remove(change_index);
80✔
1697
            }
80✔
1698
        }
56✔
1699

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

136✔
1716
        Ok(TxBuilder {
136✔
1717
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
136✔
1718
            params,
136✔
1719
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
136✔
1720
        })
136✔
1721
    }
152✔
1722

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

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

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

1782
        for signer in self
664✔
1783
            .signers
320✔
1784
            .signers()
320✔
1785
            .iter()
320✔
1786
            .chain(self.change_signers.signers().iter())
320✔
1787
        {
1788
            signer.sign_transaction(psbt, &sign_options, &self.secp)?;
664✔
1789
        }
1790

1791
        // attempt to finalize
1792
        if sign_options.try_finalize {
288✔
1793
            self.finalize_psbt(psbt, sign_options)
248✔
1794
        } else {
1795
            Ok(false)
40✔
1796
        }
1797
    }
336✔
1798

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

1806
        self.public_descriptor(keychain).extract_policy(
24✔
1807
            signers,
24✔
1808
            BuildSatisfaction::None,
24✔
1809
            &self.secp,
24✔
1810
        )
24✔
1811
    }
24✔
1812

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

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

248✔
1842
        let tx = &psbt.unsigned_tx;
248✔
1843
        let mut finished = true;
248✔
1844

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

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

264✔
1880
            match desc {
264✔
1881
                Some(desc) => {
248✔
1882
                    let mut tmp_input = bitcoin::TxIn::default();
248✔
1883
                    match desc.satisfy(
248✔
1884
                        &mut tmp_input,
248✔
1885
                        (
248✔
1886
                            PsbtInputSatisfier::new(psbt, n),
248✔
1887
                            After::new(Some(current_height), false),
248✔
1888
                            Older::new(Some(current_height), confirmation_height, false),
248✔
1889
                        ),
248✔
1890
                    ) {
248✔
1891
                        Ok(_) => {
1892
                            // Set the UTXO fields, final script_sig and witness
1893
                            // and clear everything else.
1894
                            let original = mem::take(&mut psbt.inputs[n]);
240✔
1895
                            let psbt_input = &mut psbt.inputs[n];
240✔
1896
                            psbt_input.non_witness_utxo = original.non_witness_utxo;
240✔
1897
                            psbt_input.witness_utxo = original.witness_utxo;
240✔
1898
                            if !tmp_input.script_sig.is_empty() {
240✔
1899
                                psbt_input.final_script_sig = Some(tmp_input.script_sig);
16✔
1900
                            }
224✔
1901
                            if !tmp_input.witness.is_empty() {
240✔
1902
                                psbt_input.final_script_witness = Some(tmp_input.witness);
232✔
1903
                            }
232✔
1904
                        }
1905
                        Err(_) => finished = false,
8✔
1906
                    }
1907
                }
1908
                None => finished = false,
16✔
1909
            }
1910
        }
1911

1912
        // Clear derivation paths from outputs
1913
        if finished {
240✔
1914
            for output in &mut psbt.outputs {
520✔
1915
                output.bip32_derivation.clear();
304✔
1916
                output.tap_key_origins.clear();
304✔
1917
            }
304✔
1918
        }
24✔
1919

1920
        Ok(finished)
240✔
1921
    }
248✔
1922

1923
    /// Return the secp256k1 context used for all signing operations
1924
    pub fn secp_ctx(&self) -> &SecpCtx {
28✔
1925
        &self.secp
28✔
1926
    }
28✔
1927

1928
    /// Returns the descriptor used to create addresses for a particular `keychain`.
1929
    pub fn get_descriptor_for_keychain(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,020✔
1930
        self.public_descriptor(keychain)
6,020✔
1931
    }
6,020✔
1932

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

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

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

1963
    fn get_descriptor_for_txout(&self, txout: &TxOut) -> Option<DerivedDescriptor> {
264✔
1964
        let &(keychain, child) = self
264✔
1965
            .indexed_graph
264✔
1966
            .index
264✔
1967
            .index_of_spk(&txout.script_pubkey)?;
264✔
1968
        let descriptor = self.get_descriptor_for_keychain(keychain);
248✔
1969
        descriptor.at_derivation_index(child).ok()
248✔
1970
    }
264✔
1971

1972
    fn get_available_utxos(&self) -> Vec<(LocalOutput, Weight)> {
1,128✔
1973
        self.list_unspent()
1,128✔
1974
            .map(|utxo| {
1,240✔
1975
                let keychain = utxo.keychain;
1,240✔
1976
                (utxo, {
1,240✔
1977
                    self.get_descriptor_for_keychain(keychain)
1,240✔
1978
                        .max_weight_to_satisfy()
1,240✔
1979
                        .unwrap()
1,240✔
1980
                })
1,240✔
1981
            })
1,240✔
1982
            .collect()
1,128✔
1983
    }
1,128✔
1984

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

1,128✔
2002
        let manually_selected = utxos.clone();
1,128✔
2003
        // we mandate confirmed transactions if we're bumping the fee
1,128✔
2004
        let must_only_use_confirmed_tx = bumping_fee.is_some();
1,128✔
2005
        let must_use_all_available = *drain_wallet;
1,128✔
2006

1,128✔
2007
        let chain_tip = self.chain.tip().block_id();
1,128✔
2008
        //    must_spend <- manually selected utxos
1,128✔
2009
        //    may_spend  <- all other available utxos
1,128✔
2010
        let mut may_spend = self.get_available_utxos();
1,128✔
2011

1,128✔
2012
        may_spend.retain(|may_spend| {
1,240✔
2013
            !manually_selected
1,240✔
2014
                .iter()
1,240✔
2015
                .any(|manually_selected| manually_selected.utxo.outpoint() == may_spend.0.outpoint)
1,240✔
2016
        });
1,240✔
2017
        let mut must_spend = manually_selected;
1,128✔
2018

1,128✔
2019
        // NOTE: we are intentionally ignoring `unspendable` here. i.e manual
1,128✔
2020
        // selection overrides unspendable.
1,128✔
2021
        if *manually_selected_only {
1,128✔
2022
            return (must_spend, vec![]);
40✔
2023
        }
1,088✔
2024

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

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

1,088✔
2067
        let mut i = 0;
1,088✔
2068
        may_spend.retain(|u| {
1,128✔
2069
            let retain = change_policy.is_satisfied_by(&u.0)
1,128✔
2070
                && !unspendable.contains(&u.0.outpoint)
1,120✔
2071
                && satisfies_confirmed[i];
1,120✔
2072
            i += 1;
1,128✔
2073
            retain
1,128✔
2074
        });
1,128✔
2075

1,088✔
2076
        let mut may_spend = may_spend
1,088✔
2077
            .into_iter()
1,088✔
2078
            .map(|(local_utxo, satisfaction_weight)| WeightedUtxo {
1,088✔
2079
                satisfaction_weight,
1,040✔
2080
                utxo: Utxo::Local(local_utxo),
1,040✔
2081
            })
1,088✔
2082
            .collect();
1,088✔
2083

1,088✔
2084
        if must_use_all_available {
1,088✔
2085
            must_spend.append(&mut may_spend);
392✔
2086
        }
696✔
2087

2088
        (must_spend, may_spend)
1,088✔
2089
    }
1,128✔
2090

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

2099
        if params.add_global_xpubs {
1,048✔
2100
            let all_xpubs = self
24✔
2101
                .keychains()
24✔
2102
                .flat_map(|(_, desc)| desc.get_extended_keys())
48✔
2103
                .collect::<Vec<_>>();
24✔
2104

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

2114
                psbt.xpub.insert(xpub.xkey, origin);
32✔
2115
            }
2116
        }
1,024✔
2117

2118
        let mut lookup_output = selected
1,040✔
2119
            .into_iter()
1,040✔
2120
            .map(|utxo| (utxo.outpoint(), utxo))
1,168✔
2121
            .collect::<HashMap<_, _>>();
1,040✔
2122

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

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

2165
        self.update_psbt_with_descriptor(&mut psbt)?;
1,032✔
2166

2167
        Ok(psbt)
1,032✔
2168
    }
1,048✔
2169

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

2185
        let mut psbt_input = psbt::Input {
1,128✔
2186
            sighash_type,
1,128✔
2187
            ..psbt::Input::default()
1,128✔
2188
        };
1,128✔
2189

1,128✔
2190
        let desc = self.get_descriptor_for_keychain(keychain);
1,128✔
2191
        let derived_descriptor = desc
1,128✔
2192
            .at_derivation_index(child)
1,128✔
2193
            .expect("child can't be hardened");
1,128✔
2194

1,128✔
2195
        psbt_input
1,128✔
2196
            .update_with_descriptor_unchecked(&derived_descriptor)
1,128✔
2197
            .map_err(MiniscriptPsbtError::Conversion)?;
1,128✔
2198

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

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

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

3,088✔
2235
                if is_input {
3,088✔
2236
                    psbt.update_input_with_descriptor(index, &desc)
1,424✔
2237
                        .map_err(MiniscriptPsbtError::UtxoUpdate)?;
1,424✔
2238
                } else {
2239
                    psbt.update_output_with_descriptor(index, &desc)
1,664✔
2240
                        .map_err(MiniscriptPsbtError::OutputUpdate)?;
1,664✔
2241
                }
2242
            }
576✔
2243
        }
2244

2245
        Ok(())
1,368✔
2246
    }
1,368✔
2247

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2455
    Ok(wallet_name)
×
2456
}
×
2457

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

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

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

2504
    Ok((signers, change_signers))
246✔
2505
}
248✔
2506

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

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

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

2551
        wallet
2552
    }}
2553
}
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