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

bitcoindevkit / bdk / 9475497656

12 Jun 2024 02:00AM UTC coverage: 82.974% (-0.4%) from 83.405%
9475497656

Pull #1468

github

web-flow
Merge 44e446faa into 473ef9714
Pull Request #1468: wip(feat): use `Weight` type instead of `usize`

112 of 190 new or added lines in 19 files covered. (58.95%)

13 existing lines in 3 files now uncovered.

11253 of 13562 relevant lines covered (82.97%)

16764.07 hits per line

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

81.22
/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
    IndexedTxGraph,
33
};
34
use bdk_persist::{Persist, PersistBackend};
35
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
36
use bitcoin::{
37
    absolute, psbt, Address, Block, FeeRate, Network, OutPoint, Script, ScriptBuf, Sequence,
38
    Transaction, TxOut, Txid, Witness,
39
};
40
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
41
use bitcoin::{constants::genesis_block, Amount};
42
use bitcoin::{
43
    secp256k1::{All, Secp256k1},
44
    Weight,
45
};
46
use core::fmt;
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
/// [`signer`]: crate::signer
92
#[derive(Debug)]
93
pub struct Wallet {
94
    signers: Arc<SignersContainer>,
95
    change_signers: Arc<SignersContainer>,
96
    chain: LocalChain,
97
    indexed_graph: IndexedTxGraph<ConfirmationTimeHeightAnchor, KeychainTxOutIndex<KeychainKind>>,
98
    persist: Persist<ChangeSet>,
99
    network: Network,
100
    secp: SecpCtx,
101
}
102

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

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

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

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

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

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

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

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

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

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

170
impl Wallet {
171
    /// Creates a wallet that does not persist data.
172
    pub fn new_no_persist<E: IntoWalletDescriptor>(
149✔
173
        descriptor: E,
149✔
174
        change_descriptor: E,
149✔
175
        network: Network,
149✔
176
    ) -> Result<Self, DescriptorError> {
149✔
177
        Self::new(descriptor, change_descriptor, (), network).map_err(|e| match e {
149✔
178
            NewError::NonEmptyDatabase => unreachable!("mock-database cannot have data"),
×
179
            NewError::Descriptor(e) => e,
2✔
180
            NewError::Persist(_) => unreachable!("mock-write must always succeed"),
×
181
        })
149✔
182
    }
149✔
183

184
    /// Creates a wallet that does not persist data, with a custom genesis hash.
185
    pub fn new_no_persist_with_genesis_hash<E: IntoWalletDescriptor>(
×
186
        descriptor: E,
×
187
        change_descriptor: E,
×
188
        network: Network,
×
189
        genesis_hash: BlockHash,
×
190
    ) -> Result<Self, crate::descriptor::DescriptorError> {
×
191
        Self::new_with_genesis_hash(descriptor, change_descriptor, (), network, genesis_hash)
×
192
            .map_err(|e| match e {
×
193
                NewError::NonEmptyDatabase => unreachable!("mock-database cannot have data"),
×
194
                NewError::Descriptor(e) => e,
×
195
                NewError::Persist(_) => unreachable!("mock-write must always succeed"),
×
196
            })
×
197
    }
×
198
}
199

200
/// The error type when constructing a fresh [`Wallet`].
201
///
202
/// Methods [`new`] and [`new_with_genesis_hash`] may return this error.
203
///
204
/// [`new`]: Wallet::new
205
/// [`new_with_genesis_hash`]: Wallet::new_with_genesis_hash
206
#[derive(Debug)]
207
pub enum NewError {
208
    /// Database already has data.
209
    NonEmptyDatabase,
210
    /// There was problem with the passed-in descriptor(s).
211
    Descriptor(crate::descriptor::DescriptorError),
212
    /// We were unable to write the wallet's data to the persistence backend.
213
    Persist(anyhow::Error),
214
}
215

216
impl fmt::Display for NewError {
217
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
218
        match self {
×
219
            NewError::NonEmptyDatabase => write!(
×
220
                f,
×
221
                "database already has data - use `load` or `new_or_load` methods instead"
×
222
            ),
×
223
            NewError::Descriptor(e) => e.fmt(f),
×
224
            NewError::Persist(e) => e.fmt(f),
×
225
        }
226
    }
×
227
}
228

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

232
/// The error type when loading a [`Wallet`] from persistence.
233
///
234
/// Method [`load`] may return this error.
235
///
236
/// [`load`]: Wallet::load
237
#[derive(Debug)]
238
pub enum LoadError {
239
    /// There was a problem with the passed-in descriptor(s).
240
    Descriptor(crate::descriptor::DescriptorError),
241
    /// Loading data from the persistence backend failed.
242
    Persist(anyhow::Error),
243
    /// Wallet not initialized, persistence backend is empty.
244
    NotInitialized,
245
    /// Data loaded from persistence is missing network type.
246
    MissingNetwork,
247
    /// Data loaded from persistence is missing genesis hash.
248
    MissingGenesis,
249
    /// Data loaded from persistence is missing descriptor.
250
    MissingDescriptor(KeychainKind),
251
}
252

253
impl fmt::Display for LoadError {
254
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
255
        match self {
×
256
            LoadError::Descriptor(e) => e.fmt(f),
×
257
            LoadError::Persist(e) => e.fmt(f),
×
258
            LoadError::NotInitialized => {
259
                write!(f, "wallet is not initialized, persistence backend is empty")
×
260
            }
261
            LoadError::MissingNetwork => write!(f, "loaded data is missing network type"),
×
262
            LoadError::MissingGenesis => write!(f, "loaded data is missing genesis hash"),
×
263
            LoadError::MissingDescriptor(k) => {
×
264
                write!(f, "loaded data is missing descriptor for keychain {k:?}")
×
265
            }
266
        }
267
    }
×
268
}
269

270
#[cfg(feature = "std")]
271
impl std::error::Error for LoadError {}
272

273
/// Error type for when we try load a [`Wallet`] from persistence and creating it if non-existent.
274
///
275
/// Methods [`new_or_load`] and [`new_or_load_with_genesis_hash`] may return this error.
276
///
277
/// [`new_or_load`]: Wallet::new_or_load
278
/// [`new_or_load_with_genesis_hash`]: Wallet::new_or_load_with_genesis_hash
279
#[derive(Debug)]
280
pub enum NewOrLoadError {
281
    /// There is a problem with the passed-in descriptor.
282
    Descriptor(crate::descriptor::DescriptorError),
283
    /// Either writing to or loading from the persistence backend failed.
284
    Persist(anyhow::Error),
285
    /// Wallet is not initialized, persistence backend is empty.
286
    NotInitialized,
287
    /// The loaded genesis hash does not match what was provided.
288
    LoadedGenesisDoesNotMatch {
289
        /// The expected genesis block hash.
290
        expected: BlockHash,
291
        /// The block hash loaded from persistence.
292
        got: Option<BlockHash>,
293
    },
294
    /// The loaded network type does not match what was provided.
295
    LoadedNetworkDoesNotMatch {
296
        /// The expected network type.
297
        expected: Network,
298
        /// The network type loaded from persistence.
299
        got: Option<Network>,
300
    },
301
    /// The loaded desccriptor does not match what was provided.
302
    LoadedDescriptorDoesNotMatch {
303
        /// The descriptor loaded from persistence.
304
        got: Option<ExtendedDescriptor>,
305
        /// The keychain of the descriptor not matching
306
        keychain: KeychainKind,
307
    },
308
}
309

310
impl fmt::Display for NewOrLoadError {
311
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
312
        match self {
×
313
            NewOrLoadError::Descriptor(e) => e.fmt(f),
×
314
            NewOrLoadError::Persist(e) => write!(
×
315
                f,
×
316
                "failed to either write to or load from persistence, {}",
×
317
                e
×
318
            ),
×
319
            NewOrLoadError::NotInitialized => {
320
                write!(f, "wallet is not initialized, persistence backend is empty")
×
321
            }
322
            NewOrLoadError::LoadedGenesisDoesNotMatch { expected, got } => {
×
323
                write!(f, "loaded genesis hash is not {}, got {:?}", expected, got)
×
324
            }
325
            NewOrLoadError::LoadedNetworkDoesNotMatch { expected, got } => {
×
326
                write!(f, "loaded network type is not {}, got {:?}", expected, got)
×
327
            }
328
            NewOrLoadError::LoadedDescriptorDoesNotMatch { got, keychain } => {
×
329
                write!(
×
330
                    f,
×
331
                    "loaded descriptor is different from what was provided, got {:?} for keychain {:?}",
×
332
                    got, keychain
×
333
                )
×
334
            }
335
        }
336
    }
×
337
}
338

339
#[cfg(feature = "std")]
340
impl std::error::Error for NewOrLoadError {}
341

342
/// An error that may occur when inserting a transaction into [`Wallet`].
343
#[derive(Debug)]
344
pub enum InsertTxError {
345
    /// The error variant that occurs when the caller attempts to insert a transaction with a
346
    /// confirmation height that is greater than the internal chain tip.
347
    ConfirmationHeightCannotBeGreaterThanTip {
348
        /// The internal chain's tip height.
349
        tip_height: u32,
350
        /// The introduced transaction's confirmation height.
351
        tx_height: u32,
352
    },
353
}
354

355
impl fmt::Display for InsertTxError {
356
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
357
        match self {
×
358
            InsertTxError::ConfirmationHeightCannotBeGreaterThanTip {
×
359
                tip_height,
×
360
                tx_height,
×
361
            } => {
×
362
                write!(f, "cannot insert tx with confirmation height ({}) higher than internal tip height ({})", tx_height, tip_height)
×
363
            }
×
364
        }
×
365
    }
×
366
}
367

368
#[cfg(feature = "std")]
369
impl std::error::Error for InsertTxError {}
370

371
/// An error that may occur when applying a block to [`Wallet`].
372
#[derive(Debug)]
373
pub enum ApplyBlockError {
374
    /// Occurs when the update chain cannot connect with original chain.
375
    CannotConnect(CannotConnectError),
376
    /// Occurs when the `connected_to` hash does not match the hash derived from `block`.
377
    UnexpectedConnectedToHash {
378
        /// Block hash of `connected_to`.
379
        connected_to_hash: BlockHash,
380
        /// Expected block hash of `connected_to`, as derived from `block`.
381
        expected_hash: BlockHash,
382
    },
383
}
384

385
impl fmt::Display for ApplyBlockError {
386
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
387
        match self {
×
388
            ApplyBlockError::CannotConnect(err) => err.fmt(f),
×
389
            ApplyBlockError::UnexpectedConnectedToHash {
390
                expected_hash: block_hash,
×
391
                connected_to_hash: checkpoint_hash,
×
392
            } => write!(
×
393
                f,
×
394
                "`connected_to` hash {} differs from the expected hash {} (which is derived from `block`)",
×
395
                checkpoint_hash, block_hash
×
396
            ),
×
397
        }
398
    }
×
399
}
400

401
#[cfg(feature = "std")]
402
impl std::error::Error for ApplyBlockError {}
403

404
impl Wallet {
405
    /// Initialize an empty [`Wallet`].
406
    pub fn new<E: IntoWalletDescriptor>(
153✔
407
        descriptor: E,
153✔
408
        change_descriptor: E,
153✔
409
        db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
153✔
410
        network: Network,
153✔
411
    ) -> Result<Self, NewError> {
153✔
412
        let genesis_hash = genesis_block(network).block_hash();
153✔
413
        Self::new_with_genesis_hash(descriptor, change_descriptor, db, network, genesis_hash)
153✔
414
    }
153✔
415

416
    /// Initialize an empty [`Wallet`] with a custom genesis hash.
417
    ///
418
    /// This is like [`Wallet::new`] with an additional `genesis_hash` parameter. This is useful
419
    /// for syncing from alternative networks.
420
    pub fn new_with_genesis_hash<E: IntoWalletDescriptor>(
155✔
421
        descriptor: E,
155✔
422
        change_descriptor: E,
155✔
423
        mut db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
155✔
424
        network: Network,
155✔
425
        genesis_hash: BlockHash,
155✔
426
    ) -> Result<Self, NewError> {
155✔
427
        if let Ok(changeset) = db.load_from_persistence() {
155✔
428
            if changeset.is_some() {
155✔
429
                return Err(NewError::NonEmptyDatabase);
2✔
430
            }
153✔
431
        }
×
432
        let secp = Secp256k1::new();
153✔
433
        let (chain, chain_changeset) = LocalChain::from_genesis_hash(genesis_hash);
153✔
434
        let mut index = KeychainTxOutIndex::<KeychainKind>::default();
153✔
435

436
        let (signers, change_signers) =
151✔
437
            create_signers(&mut index, &secp, descriptor, change_descriptor, network)
153✔
438
                .map_err(NewError::Descriptor)?;
153✔
439

440
        let indexed_graph = IndexedTxGraph::new(index);
151✔
441

151✔
442
        let mut persist = Persist::new(db);
151✔
443
        persist.stage(ChangeSet {
151✔
444
            chain: chain_changeset,
151✔
445
            indexed_tx_graph: indexed_graph.initial_changeset(),
151✔
446
            network: Some(network),
151✔
447
        });
151✔
448
        persist.commit().map_err(NewError::Persist)?;
151✔
449

450
        Ok(Wallet {
151✔
451
            signers,
151✔
452
            change_signers,
151✔
453
            network,
151✔
454
            chain,
151✔
455
            indexed_graph,
151✔
456
            persist,
151✔
457
            secp,
151✔
458
        })
151✔
459
    }
155✔
460

461
    /// Load [`Wallet`] from the given persistence backend.
462
    ///
463
    /// Note that the descriptor secret keys are not persisted to the db; this means that after
464
    /// calling this method the [`Wallet`] **won't** know the secret keys, and as such, won't be
465
    /// able to sign transactions.
466
    ///
467
    /// If you wish to use the wallet to sign transactions, you need to add the secret keys
468
    /// manually to the [`Wallet`]:
469
    ///
470
    /// ```rust,no_run
471
    /// # use bdk_wallet::Wallet;
472
    /// # use bdk_wallet::signer::{SignersContainer, SignerOrdering};
473
    /// # use bdk_wallet::descriptor::Descriptor;
474
    /// # use bitcoin::key::Secp256k1;
475
    /// # use bdk_wallet::KeychainKind;
476
    /// # use bdk_sqlite::{Store, rusqlite::Connection};
477
    /// #
478
    /// # fn main() -> Result<(), anyhow::Error> {
479
    /// # let temp_dir = tempfile::tempdir().expect("must create tempdir");
480
    /// # let file_path = temp_dir.path().join("store.db");
481
    /// # let conn = Connection::open(file_path).expect("must open connection");
482
    /// # let db = Store::new(conn).expect("must create db");
483
    /// let secp = Secp256k1::new();
484
    ///
485
    /// let (external_descriptor, external_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)").unwrap();
486
    /// let (internal_descriptor, internal_keymap) = Descriptor::parse_descriptor(&secp, "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)").unwrap();
487
    ///
488
    /// let external_signer_container = SignersContainer::build(external_keymap, &external_descriptor, &secp);
489
    /// let internal_signer_container = SignersContainer::build(internal_keymap, &internal_descriptor, &secp);
490
    ///
491
    /// let mut wallet = Wallet::load(db)?;
492
    ///
493
    /// external_signer_container.signers().into_iter()
494
    ///     .for_each(|s| wallet.add_signer(KeychainKind::External, SignerOrdering::default(), s.clone()));
495
    /// internal_signer_container.signers().into_iter()
496
    ///     .for_each(|s| wallet.add_signer(KeychainKind::Internal, SignerOrdering::default(), s.clone()));
497
    /// # Ok(())
498
    /// # }
499
    /// ```
500
    ///
501
    /// Alternatively, you can call [`Wallet::new_or_load`], which will add the private keys of the
502
    /// passed-in descriptors to the [`Wallet`].
503
    pub fn load(
2✔
504
        mut db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
2✔
505
    ) -> Result<Self, LoadError> {
2✔
506
        let changeset = db
2✔
507
            .load_from_persistence()
2✔
508
            .map_err(LoadError::Persist)?
2✔
509
            .ok_or(LoadError::NotInitialized)?;
2✔
510
        Self::load_from_changeset(db, changeset)
2✔
511
    }
2✔
512

513
    fn load_from_changeset(
12✔
514
        db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
12✔
515
        changeset: ChangeSet,
12✔
516
    ) -> Result<Self, LoadError> {
12✔
517
        let secp = Secp256k1::new();
12✔
518
        let network = changeset.network.ok_or(LoadError::MissingNetwork)?;
12✔
519
        let chain =
12✔
520
            LocalChain::from_changeset(changeset.chain).map_err(|_| LoadError::MissingGenesis)?;
12✔
521
        let mut index = KeychainTxOutIndex::<KeychainKind>::default();
12✔
522
        let descriptor = changeset
12✔
523
            .indexed_tx_graph
12✔
524
            .indexer
12✔
525
            .keychains_added
12✔
526
            .get(&KeychainKind::External)
12✔
527
            .ok_or(LoadError::MissingDescriptor(KeychainKind::External))?
12✔
528
            .clone();
12✔
529
        let change_descriptor = changeset
12✔
530
            .indexed_tx_graph
12✔
531
            .indexer
12✔
532
            .keychains_added
12✔
533
            .get(&KeychainKind::Internal)
12✔
534
            .ok_or(LoadError::MissingDescriptor(KeychainKind::Internal))?
12✔
535
            .clone();
12✔
536

12✔
537
        let (signers, change_signers) =
12✔
538
            create_signers(&mut index, &secp, descriptor, change_descriptor, network)
12✔
539
                .expect("Can't fail: we passed in valid descriptors, recovered from the changeset");
12✔
540

12✔
541
        let mut indexed_graph = IndexedTxGraph::new(index);
12✔
542
        indexed_graph.apply_changeset(changeset.indexed_tx_graph);
12✔
543

12✔
544
        let persist = Persist::new(db);
12✔
545

12✔
546
        Ok(Wallet {
12✔
547
            signers,
12✔
548
            change_signers,
12✔
549
            chain,
12✔
550
            indexed_graph,
12✔
551
            persist,
12✔
552
            network,
12✔
553
            secp,
12✔
554
        })
12✔
555
    }
12✔
556

557
    /// Either loads [`Wallet`] from persistence, or initializes it if it does not exist.
558
    ///
559
    /// This method will fail if the loaded [`Wallet`] has different parameters to those provided.
560
    pub fn new_or_load<E: IntoWalletDescriptor>(
10✔
561
        descriptor: E,
10✔
562
        change_descriptor: E,
10✔
563
        db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
10✔
564
        network: Network,
10✔
565
    ) -> Result<Self, NewOrLoadError> {
10✔
566
        let genesis_hash = genesis_block(network).block_hash();
10✔
567
        Self::new_or_load_with_genesis_hash(
10✔
568
            descriptor,
10✔
569
            change_descriptor,
10✔
570
            db,
10✔
571
            network,
10✔
572
            genesis_hash,
10✔
573
        )
10✔
574
    }
10✔
575

576
    /// Either loads [`Wallet`] from persistence, or initializes it if it does not exist, using the
577
    /// provided descriptor, change descriptor, network, and custom genesis hash.
578
    ///
579
    /// This method will fail if the loaded [`Wallet`] has different parameters to those provided.
580
    /// This is like [`Wallet::new_or_load`] with an additional `genesis_hash` parameter. This is
581
    /// useful for syncing from alternative networks.
582
    pub fn new_or_load_with_genesis_hash<E: IntoWalletDescriptor>(
12✔
583
        descriptor: E,
12✔
584
        change_descriptor: E,
12✔
585
        mut db: impl PersistBackend<ChangeSet> + Send + Sync + 'static,
12✔
586
        network: Network,
12✔
587
        genesis_hash: BlockHash,
12✔
588
    ) -> Result<Self, NewOrLoadError> {
12✔
589
        let changeset = db
12✔
590
            .load_from_persistence()
12✔
591
            .map_err(NewOrLoadError::Persist)?;
12✔
592
        match changeset {
12✔
593
            Some(changeset) => {
10✔
594
                let mut wallet = Self::load_from_changeset(db, changeset).map_err(|e| match e {
10✔
595
                    LoadError::Descriptor(e) => NewOrLoadError::Descriptor(e),
×
596
                    LoadError::Persist(e) => NewOrLoadError::Persist(e),
×
597
                    LoadError::NotInitialized => NewOrLoadError::NotInitialized,
×
598
                    LoadError::MissingNetwork => NewOrLoadError::LoadedNetworkDoesNotMatch {
×
599
                        expected: network,
×
600
                        got: None,
×
601
                    },
×
602
                    LoadError::MissingGenesis => NewOrLoadError::LoadedGenesisDoesNotMatch {
×
603
                        expected: genesis_hash,
×
604
                        got: None,
×
605
                    },
×
606
                    LoadError::MissingDescriptor(keychain) => {
×
607
                        NewOrLoadError::LoadedDescriptorDoesNotMatch {
×
608
                            got: None,
×
609
                            keychain,
×
610
                        }
×
611
                    }
612
                })?;
10✔
613
                if wallet.network != network {
10✔
614
                    return Err(NewOrLoadError::LoadedNetworkDoesNotMatch {
2✔
615
                        expected: network,
2✔
616
                        got: Some(wallet.network),
2✔
617
                    });
2✔
618
                }
8✔
619
                if wallet.chain.genesis_hash() != genesis_hash {
8✔
620
                    return Err(NewOrLoadError::LoadedGenesisDoesNotMatch {
2✔
621
                        expected: genesis_hash,
2✔
622
                        got: Some(wallet.chain.genesis_hash()),
2✔
623
                    });
2✔
624
                }
6✔
625

626
                let (expected_descriptor, expected_descriptor_keymap) = descriptor
6✔
627
                    .into_wallet_descriptor(&wallet.secp, network)
6✔
628
                    .map_err(NewOrLoadError::Descriptor)?;
6✔
629
                let wallet_descriptor = wallet.public_descriptor(KeychainKind::External);
6✔
630
                if wallet_descriptor != &expected_descriptor {
6✔
631
                    return Err(NewOrLoadError::LoadedDescriptorDoesNotMatch {
2✔
632
                        got: Some(wallet_descriptor.clone()),
2✔
633
                        keychain: KeychainKind::External,
2✔
634
                    });
2✔
635
                }
4✔
636
                // if expected descriptor has private keys add them as new signers
4✔
637
                if !expected_descriptor_keymap.is_empty() {
4✔
638
                    let signer_container = SignersContainer::build(
4✔
639
                        expected_descriptor_keymap,
4✔
640
                        &expected_descriptor,
4✔
641
                        &wallet.secp,
4✔
642
                    );
4✔
643
                    signer_container.signers().into_iter().for_each(|signer| {
4✔
644
                        wallet.add_signer(
4✔
645
                            KeychainKind::External,
4✔
646
                            SignerOrdering::default(),
4✔
647
                            signer.clone(),
4✔
648
                        )
4✔
649
                    });
4✔
650
                }
4✔
651

652
                let (expected_change_descriptor, expected_change_descriptor_keymap) =
4✔
653
                    change_descriptor
4✔
654
                        .into_wallet_descriptor(&wallet.secp, network)
4✔
655
                        .map_err(NewOrLoadError::Descriptor)?;
4✔
656
                let wallet_change_descriptor = wallet.public_descriptor(KeychainKind::Internal);
4✔
657
                if wallet_change_descriptor != &expected_change_descriptor {
4✔
658
                    return Err(NewOrLoadError::LoadedDescriptorDoesNotMatch {
2✔
659
                        got: Some(wallet_change_descriptor.clone()),
2✔
660
                        keychain: KeychainKind::Internal,
2✔
661
                    });
2✔
662
                }
2✔
663
                // if expected change descriptor has private keys add them as new signers
2✔
664
                if !expected_change_descriptor_keymap.is_empty() {
2✔
665
                    let signer_container = SignersContainer::build(
2✔
666
                        expected_change_descriptor_keymap,
2✔
667
                        &expected_change_descriptor,
2✔
668
                        &wallet.secp,
2✔
669
                    );
2✔
670
                    signer_container.signers().into_iter().for_each(|signer| {
2✔
671
                        wallet.add_signer(
2✔
672
                            KeychainKind::Internal,
2✔
673
                            SignerOrdering::default(),
2✔
674
                            signer.clone(),
2✔
675
                        )
2✔
676
                    });
2✔
677
                }
2✔
678

679
                Ok(wallet)
2✔
680
            }
681
            None => Self::new_with_genesis_hash(
2✔
682
                descriptor,
2✔
683
                change_descriptor,
2✔
684
                db,
2✔
685
                network,
2✔
686
                genesis_hash,
2✔
687
            )
2✔
688
            .map_err(|e| match e {
2✔
689
                NewError::NonEmptyDatabase => {
690
                    unreachable!("database is already checked to have no data")
×
691
                }
692
                NewError::Descriptor(e) => NewOrLoadError::Descriptor(e),
×
693
                NewError::Persist(e) => NewOrLoadError::Persist(e),
×
694
            }),
2✔
695
        }
696
    }
12✔
697

698
    /// Get the Bitcoin network the wallet is using.
699
    pub fn network(&self) -> Network {
48✔
700
        self.network
48✔
701
    }
48✔
702

703
    /// Iterator over all keychains in this wallet
704
    pub fn keychains(&self) -> impl Iterator<Item = (&KeychainKind, &ExtendedDescriptor)> {
64✔
705
        self.indexed_graph.index.keychains()
64✔
706
    }
64✔
707

708
    /// Peek an address of the given `keychain` at `index` without revealing it.
709
    ///
710
    /// For non-wildcard descriptors this returns the same address at every provided index.
711
    ///
712
    /// # Panics
713
    ///
714
    /// This panics when the caller requests for an address of derivation index greater than the
715
    /// [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) max index.
716
    pub fn peek_address(&self, keychain: KeychainKind, mut index: u32) -> AddressInfo {
1,248✔
717
        let mut spk_iter = self
1,248✔
718
            .indexed_graph
1,248✔
719
            .index
1,248✔
720
            .unbounded_spk_iter(&keychain)
1,248✔
721
            .expect("keychain must exist");
1,248✔
722
        if !spk_iter.descriptor().has_wildcard() {
1,248✔
723
            index = 0;
952✔
724
        }
952✔
725
        let (index, spk) = spk_iter
1,248✔
726
            .nth(index as usize)
1,248✔
727
            .expect("derivation index is out of bounds");
1,248✔
728

1,248✔
729
        AddressInfo {
1,248✔
730
            index,
1,248✔
731
            address: Address::from_script(&spk, self.network).expect("must have address form"),
1,248✔
732
            keychain,
1,248✔
733
        }
1,248✔
734
    }
1,248✔
735

736
    /// Attempt to reveal the next address of the given `keychain`.
737
    ///
738
    /// This will increment the internal derivation index. If the keychain's descriptor doesn't
739
    /// contain a wildcard or every address is already revealed up to the maximum derivation
740
    /// index defined in [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
741
    /// then returns the last revealed address.
742
    ///
743
    /// # Errors
744
    ///
745
    /// If writing to persistent storage fails.
746
    pub fn reveal_next_address(&mut self, keychain: KeychainKind) -> anyhow::Result<AddressInfo> {
120✔
747
        let ((index, spk), index_changeset) = self
120✔
748
            .indexed_graph
120✔
749
            .index
120✔
750
            .reveal_next_spk(&keychain)
120✔
751
            .expect("keychain must exist");
120✔
752

120✔
753
        self.persist
120✔
754
            .stage_and_commit(indexed_tx_graph::ChangeSet::from(index_changeset).into())?;
120✔
755

756
        Ok(AddressInfo {
120✔
757
            index,
120✔
758
            address: Address::from_script(spk, self.network).expect("must have address form"),
120✔
759
            keychain,
120✔
760
        })
120✔
761
    }
120✔
762

763
    /// Reveal addresses up to and including the target `index` and return an iterator
764
    /// of newly revealed addresses.
765
    ///
766
    /// If the target `index` is unreachable, we make a best effort to reveal up to the last
767
    /// possible index. If all addresses up to the given `index` are already revealed, then
768
    /// no new addresses are returned.
769
    ///
770
    /// # Errors
771
    ///
772
    /// If writing to persistent storage fails.
773
    pub fn reveal_addresses_to(
16✔
774
        &mut self,
16✔
775
        keychain: KeychainKind,
16✔
776
        index: u32,
16✔
777
    ) -> anyhow::Result<impl Iterator<Item = AddressInfo> + '_> {
16✔
778
        let (spk_iter, index_changeset) = self
16✔
779
            .indexed_graph
16✔
780
            .index
16✔
781
            .reveal_to_target(&keychain, index)
16✔
782
            .expect("keychain must exist");
16✔
783

16✔
784
        self.persist
16✔
785
            .stage_and_commit(indexed_tx_graph::ChangeSet::from(index_changeset).into())?;
16✔
786

787
        Ok(spk_iter.map(move |(index, spk)| AddressInfo {
24✔
788
            index,
10✔
789
            address: Address::from_script(&spk, self.network).expect("must have address form"),
10✔
790
            keychain,
10✔
791
        }))
24✔
792
    }
16✔
793

794
    /// Get the next unused address for the given `keychain`, i.e. the address with the lowest
795
    /// derivation index that hasn't been used.
796
    ///
797
    /// This will attempt to derive and reveal a new address if no newly revealed addresses
798
    /// are available. See also [`reveal_next_address`](Self::reveal_next_address).
799
    ///
800
    /// # Errors
801
    ///
802
    /// If writing to persistent storage fails.
803
    pub fn next_unused_address(&mut self, keychain: KeychainKind) -> anyhow::Result<AddressInfo> {
896✔
804
        let ((index, spk), index_changeset) = self
896✔
805
            .indexed_graph
896✔
806
            .index
896✔
807
            .next_unused_spk(&keychain)
896✔
808
            .expect("keychain must exist");
896✔
809

896✔
810
        self.persist
896✔
811
            .stage_and_commit(indexed_tx_graph::ChangeSet::from(index_changeset).into())?;
896✔
812

813
        Ok(AddressInfo {
896✔
814
            index,
896✔
815
            address: Address::from_script(spk, self.network).expect("must have address form"),
896✔
816
            keychain,
896✔
817
        })
896✔
818
    }
896✔
819

820
    /// Marks an address used of the given `keychain` at `index`.
821
    ///
822
    /// Returns whether the given index was present and then removed from the unused set.
823
    pub fn mark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
8✔
824
        self.indexed_graph.index.mark_used(keychain, index)
8✔
825
    }
8✔
826

827
    /// Undoes the effect of [`mark_used`] and returns whether the `index` was inserted
828
    /// back into the unused set.
829
    ///
830
    /// Since this is only a superficial marker, it will have no effect if the address at the given
831
    /// `index` was actually used, i.e. the wallet has previously indexed a tx output for the
832
    /// derived spk.
833
    ///
834
    /// [`mark_used`]: Self::mark_used
835
    pub fn unmark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
16✔
836
        self.indexed_graph.index.unmark_used(keychain, index)
16✔
837
    }
16✔
838

839
    /// List addresses that are revealed but unused.
840
    ///
841
    /// Note if the returned iterator is empty you can reveal more addresses
842
    /// by using [`reveal_next_address`](Self::reveal_next_address) or
843
    /// [`reveal_addresses_to`](Self::reveal_addresses_to).
844
    pub fn list_unused_addresses(
24✔
845
        &self,
24✔
846
        keychain: KeychainKind,
24✔
847
    ) -> impl DoubleEndedIterator<Item = AddressInfo> + '_ {
24✔
848
        self.indexed_graph
24✔
849
            .index
24✔
850
            .unused_keychain_spks(&keychain)
24✔
851
            .map(move |(index, spk)| AddressInfo {
32✔
852
                index,
11✔
853
                address: Address::from_script(spk, self.network).expect("must have address form"),
11✔
854
                keychain,
11✔
855
            })
32✔
856
    }
24✔
857

858
    /// Return whether or not a `script` is part of this wallet (either internal or external)
859
    pub fn is_mine(&self, script: &Script) -> bool {
1,768✔
860
        self.indexed_graph.index.index_of_spk(script).is_some()
1,768✔
861
    }
1,768✔
862

863
    /// Finds how the wallet derived the script pubkey `spk`.
864
    ///
865
    /// Will only return `Some(_)` if the wallet has given out the spk.
866
    pub fn derivation_of_spk(&self, spk: &Script) -> Option<(KeychainKind, u32)> {
64✔
867
        self.indexed_graph.index.index_of_spk(spk)
64✔
868
    }
64✔
869

870
    /// Return the list of unspent outputs of this wallet
871
    pub fn list_unspent(&self) -> impl Iterator<Item = LocalOutput> + '_ {
1,200✔
872
        self.indexed_graph
1,200✔
873
            .graph()
1,200✔
874
            .filter_chain_unspents(
1,200✔
875
                &self.chain,
1,200✔
876
                self.chain.tip().block_id(),
1,200✔
877
                self.indexed_graph.index.outpoints(),
1,200✔
878
            )
1,200✔
879
            .map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
1,312✔
880
    }
1,200✔
881

882
    /// List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).
883
    ///
884
    /// To list only unspent outputs (UTXOs), use [`Wallet::list_unspent`] instead.
885
    pub fn list_output(&self) -> impl Iterator<Item = LocalOutput> + '_ {
8✔
886
        self.indexed_graph
8✔
887
            .graph()
8✔
888
            .filter_chain_txouts(
8✔
889
                &self.chain,
8✔
890
                self.chain.tip().block_id(),
8✔
891
                self.indexed_graph.index.outpoints(),
8✔
892
            )
8✔
893
            .map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
9✔
894
    }
8✔
895

896
    /// Get all the checkpoints the wallet is currently storing indexed by height.
897
    pub fn checkpoints(&self) -> CheckPointIter {
×
898
        self.chain.iter_checkpoints()
×
899
    }
×
900

901
    /// Returns the latest checkpoint.
902
    pub fn latest_checkpoint(&self) -> CheckPoint {
72✔
903
        self.chain.tip()
72✔
904
    }
72✔
905

906
    /// Get unbounded script pubkey iterators for both `Internal` and `External` keychains.
907
    ///
908
    /// This is intended to be used when doing a full scan of your addresses (e.g. after restoring
909
    /// from seed words). You pass the `BTreeMap` of iterators to a blockchain data source (e.g.
910
    /// electrum server) which will go through each address until it reaches a *stop gap*.
911
    ///
912
    /// Note carefully that iterators go over **all** script pubkeys on the keychains (not what
913
    /// script pubkeys the wallet is storing internally).
914
    pub fn all_unbounded_spk_iters(
×
915
        &self,
×
916
    ) -> BTreeMap<KeychainKind, impl Iterator<Item = (u32, ScriptBuf)> + Clone> {
×
917
        self.indexed_graph.index.all_unbounded_spk_iters()
×
918
    }
×
919

920
    /// Get an unbounded script pubkey iterator for the given `keychain`.
921
    ///
922
    /// See [`all_unbounded_spk_iters`] for more documentation
923
    ///
924
    /// [`all_unbounded_spk_iters`]: Self::all_unbounded_spk_iters
925
    pub fn unbounded_spk_iter(
×
926
        &self,
×
927
        keychain: KeychainKind,
×
928
    ) -> impl Iterator<Item = (u32, ScriptBuf)> + Clone {
×
929
        self.indexed_graph
×
930
            .index
×
931
            .unbounded_spk_iter(&keychain)
×
932
            .expect("keychain must exist")
×
933
    }
×
934

935
    /// Returns the utxo owned by this wallet corresponding to `outpoint` if it exists in the
936
    /// wallet's database.
937
    pub fn get_utxo(&self, op: OutPoint) -> Option<LocalOutput> {
72✔
938
        let (keychain, index, _) = self.indexed_graph.index.txout(op)?;
72✔
939
        self.indexed_graph
72✔
940
            .graph()
72✔
941
            .filter_chain_unspents(
72✔
942
                &self.chain,
72✔
943
                self.chain.tip().block_id(),
72✔
944
                core::iter::once(((), op)),
72✔
945
            )
72✔
946
            .map(|(_, full_txo)| new_local_utxo(keychain, index, full_txo))
72✔
947
            .next()
72✔
948
    }
72✔
949

950
    /// Inserts a [`TxOut`] at [`OutPoint`] into the wallet's transaction graph.
951
    ///
952
    /// This is used for providing a previous output's value so that we can use [`calculate_fee`]
953
    /// or [`calculate_fee_rate`] on a given transaction. Outputs inserted with this method will
954
    /// not be returned in [`list_unspent`] or [`list_output`].
955
    ///
956
    /// Any inserted `TxOut`s are not persisted until [`commit`] is called.
957
    ///
958
    /// **WARNING:** This should only be used to add `TxOut`s that the wallet does not own. Only
959
    /// insert `TxOut`s that you trust the values for!
960
    ///
961
    /// [`calculate_fee`]: Self::calculate_fee
962
    /// [`calculate_fee_rate`]: Self::calculate_fee_rate
963
    /// [`list_unspent`]: Self::list_unspent
964
    /// [`list_output`]: Self::list_output
965
    /// [`commit`]: Self::commit
966
    pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) {
16✔
967
        let additions = self.indexed_graph.insert_txout(outpoint, txout);
16✔
968
        self.persist.stage(ChangeSet::from(additions));
16✔
969
    }
16✔
970

971
    /// Calculates the fee of a given transaction. Returns [`Amount::ZERO`] if `tx` is a coinbase transaction.
972
    ///
973
    /// To calculate the fee for a [`Transaction`] with inputs not owned by this wallet you must
974
    /// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
975
    ///
976
    /// Note `tx` does not have to be in the graph for this to work.
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("transaction").tx_node.tx;
986
    /// let fee = wallet.calculate_fee(&tx).expect("fee");
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 fee = wallet.calculate_fee(tx).expect("fee");
996
    /// ```
997
    /// [`insert_txout`]: Self::insert_txout
998
    pub fn calculate_fee(&self, tx: &Transaction) -> Result<Amount, CalculateFeeError> {
536✔
999
        self.indexed_graph.graph().calculate_fee(tx)
536✔
1000
    }
536✔
1001

1002
    /// Calculate the [`FeeRate`] for a given transaction.
1003
    ///
1004
    /// To calculate the fee rate for a [`Transaction`] with inputs not owned by this wallet you must
1005
    /// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
1006
    ///
1007
    /// Note `tx` does not have to be in the graph for this to work.
1008
    ///
1009
    /// # Examples
1010
    ///
1011
    /// ```rust, no_run
1012
    /// # use bitcoin::Txid;
1013
    /// # use bdk_wallet::Wallet;
1014
    /// # let mut wallet: Wallet = todo!();
1015
    /// # let txid:Txid = todo!();
1016
    /// let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
1017
    /// let fee_rate = wallet.calculate_fee_rate(&tx).expect("fee rate");
1018
    /// ```
1019
    ///
1020
    /// ```rust, no_run
1021
    /// # use bitcoin::Psbt;
1022
    /// # use bdk_wallet::Wallet;
1023
    /// # let mut wallet: Wallet = todo!();
1024
    /// # let mut psbt: Psbt = todo!();
1025
    /// let tx = &psbt.clone().extract_tx().expect("tx");
1026
    /// let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
1027
    /// ```
1028
    /// [`insert_txout`]: Self::insert_txout
1029
    pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<FeeRate, CalculateFeeError> {
144✔
1030
        self.calculate_fee(tx).map(|fee| fee / tx.weight())
144✔
1031
    }
144✔
1032

1033
    /// Compute the `tx`'s sent and received [`Amount`]s.
1034
    ///
1035
    /// This method returns a tuple `(sent, received)`. Sent is the sum of the txin amounts
1036
    /// that spend from previous txouts tracked by this wallet. Received is the summation
1037
    /// of this tx's outputs that send to script pubkeys tracked by this wallet.
1038
    ///
1039
    /// # Examples
1040
    ///
1041
    /// ```rust, no_run
1042
    /// # use bitcoin::Txid;
1043
    /// # use bdk_wallet::Wallet;
1044
    /// # let mut wallet: Wallet = todo!();
1045
    /// # let txid:Txid = todo!();
1046
    /// let tx = wallet.get_tx(txid).expect("tx exists").tx_node.tx;
1047
    /// let (sent, received) = wallet.sent_and_received(&tx);
1048
    /// ```
1049
    ///
1050
    /// ```rust, no_run
1051
    /// # use bitcoin::Psbt;
1052
    /// # use bdk_wallet::Wallet;
1053
    /// # let mut wallet: Wallet = todo!();
1054
    /// # let mut psbt: Psbt = todo!();
1055
    /// let tx = &psbt.clone().extract_tx().expect("tx");
1056
    /// let (sent, received) = wallet.sent_and_received(tx);
1057
    /// ```
1058
    pub fn sent_and_received(&self, tx: &Transaction) -> (Amount, Amount) {
224✔
1059
        self.indexed_graph.index.sent_and_received(tx, ..)
224✔
1060
    }
224✔
1061

1062
    /// Get a single transaction from the wallet as a [`CanonicalTx`] (if the transaction exists).
1063
    ///
1064
    /// `CanonicalTx` contains the full transaction alongside meta-data such as:
1065
    /// * Blocks that the transaction is [`Anchor`]ed in. These may or may not be blocks that exist
1066
    ///   in the best chain.
1067
    /// * The [`ChainPosition`] of the transaction in the best chain - whether the transaction is
1068
    ///   confirmed or unconfirmed. If the transaction is confirmed, the anchor which proves the
1069
    ///   confirmation is provided. If the transaction is unconfirmed, the unix timestamp of when
1070
    ///   the transaction was last seen in the mempool is provided.
1071
    ///
1072
    /// ```rust, no_run
1073
    /// use bdk_chain::Anchor;
1074
    /// use bdk_wallet::{chain::ChainPosition, Wallet};
1075
    /// # let wallet: Wallet = todo!();
1076
    /// # let my_txid: bitcoin::Txid = todo!();
1077
    ///
1078
    /// let canonical_tx = wallet.get_tx(my_txid).expect("panic if tx does not exist");
1079
    ///
1080
    /// // get reference to full transaction
1081
    /// println!("my tx: {:#?}", canonical_tx.tx_node.tx);
1082
    ///
1083
    /// // list all transaction anchors
1084
    /// for anchor in canonical_tx.tx_node.anchors {
1085
    ///     println!(
1086
    ///         "tx is anchored by block of hash {}",
1087
    ///         anchor.anchor_block().hash
1088
    ///     );
1089
    /// }
1090
    ///
1091
    /// // get confirmation status of transaction
1092
    /// match canonical_tx.chain_position {
1093
    ///     ChainPosition::Confirmed(anchor) => println!(
1094
    ///         "tx is confirmed at height {}, we know this since {}:{} is in the best chain",
1095
    ///         anchor.confirmation_height, anchor.anchor_block.height, anchor.anchor_block.hash,
1096
    ///     ),
1097
    ///     ChainPosition::Unconfirmed(last_seen) => println!(
1098
    ///         "tx is last seen at {}, it is unconfirmed as it is not anchored in the best chain",
1099
    ///         last_seen,
1100
    ///     ),
1101
    /// }
1102
    /// ```
1103
    ///
1104
    /// [`Anchor`]: bdk_chain::Anchor
1105
    pub fn get_tx(
56✔
1106
        &self,
56✔
1107
        txid: Txid,
56✔
1108
    ) -> Option<CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> {
56✔
1109
        let graph = self.indexed_graph.graph();
56✔
1110

56✔
1111
        Some(CanonicalTx {
56✔
1112
            chain_position: graph.get_chain_position(
56✔
1113
                &self.chain,
56✔
1114
                self.chain.tip().block_id(),
56✔
1115
                txid,
56✔
1116
            )?,
56✔
1117
            tx_node: graph.get_tx_node(txid)?,
56✔
1118
        })
1119
    }
56✔
1120

1121
    /// Add a new checkpoint to the wallet's internal view of the chain.
1122
    /// This stages but does not [`commit`] the change.
1123
    ///
1124
    /// Returns whether anything changed with the insertion (e.g. `false` if checkpoint was already
1125
    /// there).
1126
    ///
1127
    /// [`commit`]: Self::commit
1128
    pub fn insert_checkpoint(
2,158✔
1129
        &mut self,
2,158✔
1130
        block_id: BlockId,
2,158✔
1131
    ) -> Result<bool, local_chain::AlterCheckPointError> {
2,158✔
1132
        let changeset = self.chain.insert_block(block_id)?;
2,158✔
1133
        let changed = !changeset.is_empty();
2,158✔
1134
        self.persist.stage(changeset.into());
2,158✔
1135
        Ok(changed)
2,158✔
1136
    }
2,158✔
1137

1138
    /// Add a transaction to the wallet's internal view of the chain. This stages but does not
1139
    /// [`commit`] the change.
1140
    ///
1141
    /// Returns whether anything changed with the transaction insertion (e.g. `false` if the
1142
    /// transaction was already inserted at the same position).
1143
    ///
1144
    /// A `tx` can be rejected if `position` has a height greater than the [`latest_checkpoint`].
1145
    /// Therefore you should use [`insert_checkpoint`] to insert new checkpoints before manually
1146
    /// inserting new transactions.
1147
    ///
1148
    /// **WARNING:** If `position` is confirmed, we anchor the `tx` to a the lowest checkpoint that
1149
    /// is >= the `position`'s height. The caller is responsible for ensuring the `tx` exists in our
1150
    /// local view of the best chain's history.
1151
    ///
1152
    /// [`commit`]: Self::commit
1153
    /// [`latest_checkpoint`]: Self::latest_checkpoint
1154
    /// [`insert_checkpoint`]: Self::insert_checkpoint
1155
    pub fn insert_tx(
2,414✔
1156
        &mut self,
2,414✔
1157
        tx: Transaction,
2,414✔
1158
        position: ConfirmationTime,
2,414✔
1159
    ) -> Result<bool, InsertTxError> {
2,414✔
1160
        let (anchor, last_seen) = match position {
2,414✔
1161
            ConfirmationTime::Confirmed { height, time } => {
2,230✔
1162
                // anchor tx to checkpoint with lowest height that is >= position's height
1163
                let anchor = self
2,230✔
1164
                    .chain
2,230✔
1165
                    .range(height..)
2,230✔
1166
                    .last()
2,230✔
1167
                    .ok_or(InsertTxError::ConfirmationHeightCannotBeGreaterThanTip {
2,230✔
1168
                        tip_height: self.chain.tip().height(),
2,230✔
1169
                        tx_height: height,
2,230✔
1170
                    })
2,230✔
1171
                    .map(|anchor_cp| ConfirmationTimeHeightAnchor {
2,230✔
1172
                        anchor_block: anchor_cp.block_id(),
2,230✔
1173
                        confirmation_height: height,
2,230✔
1174
                        confirmation_time: time,
2,230✔
1175
                    })?;
2,230✔
1176

1177
                (Some(anchor), None)
2,230✔
1178
            }
1179
            ConfirmationTime::Unconfirmed { last_seen } => (None, Some(last_seen)),
184✔
1180
        };
1181

1182
        let mut changeset = ChangeSet::default();
2,414✔
1183
        let txid = tx.compute_txid();
2,414✔
1184
        changeset.append(self.indexed_graph.insert_tx(tx).into());
2,414✔
1185
        if let Some(anchor) = anchor {
2,414✔
1186
            changeset.append(self.indexed_graph.insert_anchor(txid, anchor).into());
2,230✔
1187
        }
2,230✔
1188
        if let Some(last_seen) = last_seen {
2,414✔
1189
            changeset.append(self.indexed_graph.insert_seen_at(txid, last_seen).into());
184✔
1190
        }
2,230✔
1191

1192
        let changed = !changeset.is_empty();
2,414✔
1193
        self.persist.stage(changeset);
2,414✔
1194
        Ok(changed)
2,414✔
1195
    }
2,414✔
1196

1197
    /// Iterate over the transactions in the wallet.
1198
    pub fn transactions(
38✔
1199
        &self,
38✔
1200
    ) -> impl Iterator<Item = CanonicalTx<'_, Arc<Transaction>, ConfirmationTimeHeightAnchor>> + '_
38✔
1201
    {
38✔
1202
        self.indexed_graph
38✔
1203
            .graph()
38✔
1204
            .list_chain_txs(&self.chain, self.chain.tip().block_id())
38✔
1205
    }
38✔
1206

1207
    /// Return the balance, separated into available, trusted-pending, untrusted-pending and immature
1208
    /// values.
1209
    pub fn balance(&self) -> Balance {
32✔
1210
        self.indexed_graph.graph().balance(
32✔
1211
            &self.chain,
32✔
1212
            self.chain.tip().block_id(),
32✔
1213
            self.indexed_graph.index.outpoints(),
32✔
1214
            |&(k, _), _| k == KeychainKind::Internal,
32✔
1215
        )
32✔
1216
    }
32✔
1217

1218
    /// Add an external signer
1219
    ///
1220
    /// See [the `signer` module](signer) for an example.
1221
    pub fn add_signer(
64✔
1222
        &mut self,
64✔
1223
        keychain: KeychainKind,
64✔
1224
        ordering: SignerOrdering,
64✔
1225
        signer: Arc<dyn TransactionSigner>,
64✔
1226
    ) {
64✔
1227
        let signers = match keychain {
64✔
1228
            KeychainKind::External => Arc::make_mut(&mut self.signers),
48✔
1229
            KeychainKind::Internal => Arc::make_mut(&mut self.change_signers),
16✔
1230
        };
1231

1232
        signers.add_external(signer.id(&self.secp), ordering, signer);
64✔
1233
    }
64✔
1234

1235
    /// Get the signers
1236
    ///
1237
    /// ## Example
1238
    ///
1239
    /// ```
1240
    /// # use bdk_wallet::{Wallet, KeychainKind};
1241
    /// # use bdk_wallet::bitcoin::Network;
1242
    /// let descriptor = "wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/1'/0'/0/*)";
1243
    /// let change_descriptor = "wpkh(tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/1'/0'/1/*)";
1244
    /// let wallet = Wallet::new_no_persist(descriptor, change_descriptor, Network::Testnet)?;
1245
    /// for secret_key in wallet.get_signers(KeychainKind::External).signers().iter().filter_map(|s| s.descriptor_secret_key()) {
1246
    ///     // secret_key: tprv8ZgxMBicQKsPe73PBRSmNbTfbcsZnwWhz5eVmhHpi31HW29Z7mc9B4cWGRQzopNUzZUT391DeDJxL2PefNunWyLgqCKRMDkU1s2s8bAfoSk/84'/0'/0'/0/*
1247
    ///     println!("secret_key: {}", secret_key);
1248
    /// }
1249
    ///
1250
    /// Ok::<(), Box<dyn std::error::Error>>(())
1251
    /// ```
1252
    pub fn get_signers(&self, keychain: KeychainKind) -> Arc<SignersContainer> {
36✔
1253
        match keychain {
36✔
1254
            KeychainKind::External => Arc::clone(&self.signers),
22✔
1255
            KeychainKind::Internal => Arc::clone(&self.change_signers),
14✔
1256
        }
1257
    }
36✔
1258

1259
    /// Start building a transaction.
1260
    ///
1261
    /// This returns a blank [`TxBuilder`] from which you can specify the parameters for the transaction.
1262
    ///
1263
    /// ## Example
1264
    ///
1265
    /// ```
1266
    /// # use std::str::FromStr;
1267
    /// # use bitcoin::*;
1268
    /// # use bdk_wallet::*;
1269
    /// # use bdk_wallet::wallet::ChangeSet;
1270
    /// # use bdk_wallet::wallet::error::CreateTxError;
1271
    /// # use bdk_persist::PersistBackend;
1272
    /// # use anyhow::Error;
1273
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1274
    /// # let mut wallet = doctest_wallet!();
1275
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1276
    /// let psbt = {
1277
    ///    let mut builder =  wallet.build_tx();
1278
    ///    builder
1279
    ///        .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
1280
    ///    builder.finish()?
1281
    /// };
1282
    ///
1283
    /// // sign and broadcast ...
1284
    /// # Ok::<(), anyhow::Error>(())
1285
    /// ```
1286
    ///
1287
    /// [`TxBuilder`]: crate::TxBuilder
1288
    pub fn build_tx(&mut self) -> TxBuilder<'_, DefaultCoinSelectionAlgorithm> {
1,096✔
1289
        TxBuilder {
1,096✔
1290
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
1,096✔
1291
            params: TxParams::default(),
1,096✔
1292
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
1,096✔
1293
        }
1,096✔
1294
    }
1,096✔
1295

1296
    pub(crate) fn create_tx<Cs: coin_selection::CoinSelectionAlgorithm>(
146✔
1297
        &mut self,
146✔
1298
        coin_selection: Cs,
146✔
1299
        params: TxParams,
146✔
1300
    ) -> Result<Psbt, CreateTxError> {
146✔
1301
        let keychains: BTreeMap<_, _> = self.indexed_graph.index.keychains().collect();
146✔
1302
        let external_descriptor = keychains.get(&KeychainKind::External).expect("must exist");
146✔
1303
        let internal_descriptor = keychains.get(&KeychainKind::Internal).expect("must exist");
146✔
1304

1305
        let external_policy = external_descriptor
146✔
1306
            .extract_policy(&self.signers, BuildSatisfaction::None, &self.secp)?
146✔
1307
            .unwrap();
146✔
1308
        let internal_policy = internal_descriptor
146✔
1309
            .extract_policy(&self.change_signers, BuildSatisfaction::None, &self.secp)?
146✔
1310
            .unwrap();
146✔
1311

146✔
1312
        // The policy allows spending external outputs, but it requires a policy path that hasn't been
146✔
1313
        // provided
146✔
1314
        if params.change_policy != tx_builder::ChangeSpendPolicy::OnlyChange
146✔
1315
            && external_policy.requires_path()
145✔
1316
            && params.external_policy_path.is_none()
4✔
1317
        {
1318
            return Err(CreateTxError::SpendingPolicyRequired(
1✔
1319
                KeychainKind::External,
1✔
1320
            ));
1✔
1321
        };
145✔
1322
        // Same for the internal_policy path
145✔
1323
        if params.change_policy != tx_builder::ChangeSpendPolicy::ChangeForbidden
145✔
1324
            && internal_policy.requires_path()
144✔
1325
            && params.internal_policy_path.is_none()
×
1326
        {
1327
            return Err(CreateTxError::SpendingPolicyRequired(
×
1328
                KeychainKind::Internal,
×
1329
            ));
×
1330
        };
145✔
1331

1332
        let external_requirements = external_policy.get_condition(
145✔
1333
            params
145✔
1334
                .external_policy_path
145✔
1335
                .as_ref()
145✔
1336
                .unwrap_or(&BTreeMap::new()),
145✔
1337
        )?;
145✔
1338
        let internal_requirements = internal_policy.get_condition(
145✔
1339
            params
145✔
1340
                .internal_policy_path
145✔
1341
                .as_ref()
145✔
1342
                .unwrap_or(&BTreeMap::new()),
145✔
1343
        )?;
145✔
1344

1345
        let requirements = external_requirements.merge(&internal_requirements)?;
145✔
1346

1347
        let version = match params.version {
143✔
1348
            Some(tx_builder::Version(0)) => return Err(CreateTxError::Version0),
1✔
1349
            Some(tx_builder::Version(1)) if requirements.csv.is_some() => {
18✔
1350
                return Err(CreateTxError::Version1Csv)
1✔
1351
            }
1352
            Some(tx_builder::Version(x)) => x,
18✔
1353
            None if requirements.csv.is_some() => 2,
125✔
1354
            None => 1,
121✔
1355
        };
1356

1357
        // We use a match here instead of a unwrap_or_else as it's way more readable :)
1358
        let current_height = match params.current_height {
143✔
1359
            // If they didn't tell us the current height, we assume it's the latest sync height.
1360
            None => {
1361
                let tip_height = self.chain.tip().height();
139✔
1362
                absolute::LockTime::from_height(tip_height).expect("invalid height")
139✔
1363
            }
1364
            Some(h) => h,
4✔
1365
        };
1366

1367
        let lock_time = match params.locktime {
142✔
1368
            // When no nLockTime is specified, we try to prevent fee sniping, if possible
1369
            None => {
1370
                // Fee sniping can be partially prevented by setting the timelock
1371
                // to current_height. If we don't know the current_height,
1372
                // we default to 0.
1373
                let fee_sniping_height = current_height;
140✔
1374

1375
                // We choose the biggest between the required nlocktime and the fee sniping
1376
                // height
1377
                match requirements.timelock {
4✔
1378
                    // No requirement, just use the fee_sniping_height
1379
                    None => fee_sniping_height,
136✔
1380
                    // There's a block-based requirement, but the value is lower than the fee_sniping_height
1381
                    Some(value @ absolute::LockTime::Blocks(_)) if value < fee_sniping_height => {
4✔
1382
                        fee_sniping_height
×
1383
                    }
1384
                    // There's a time-based requirement or a block-based requirement greater
1385
                    // than the fee_sniping_height use that value
1386
                    Some(value) => value,
4✔
1387
                }
1388
            }
1389
            // Specific nLockTime required and we have no constraints, so just set to that value
1390
            Some(x) if requirements.timelock.is_none() => x,
3✔
1391
            // Specific nLockTime required and it's compatible with the constraints
1392
            Some(x)
1✔
1393
                if requirements.timelock.unwrap().is_same_unit(x)
2✔
1394
                    && x >= requirements.timelock.unwrap() =>
2✔
1395
            {
1✔
1396
                x
1✔
1397
            }
1398
            // Invalid nLockTime required
1399
            Some(x) => {
1✔
1400
                return Err(CreateTxError::LockTime {
1✔
1401
                    requested: x,
1✔
1402
                    required: requirements.timelock.unwrap(),
1✔
1403
                })
1✔
1404
            }
1405
        };
1406

1407
        // The nSequence to be by default for inputs unless an explicit sequence is specified.
1408
        let n_sequence = match (params.rbf, requirements.csv) {
142✔
1409
            // No RBF or CSV but there's an nLockTime, so the nSequence cannot be final
1410
            (None, None) if lock_time != absolute::LockTime::ZERO => {
117✔
1411
                Sequence::ENABLE_LOCKTIME_NO_RBF
116✔
1412
            }
1413
            // No RBF, CSV or nLockTime, make the transaction final
1414
            (None, None) => Sequence::MAX,
1✔
1415

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

1421
            // RBF with a specific value but that value is too high
1422
            (Some(tx_builder::RbfValue::Value(rbf)), _) if !rbf.is_rbf() => {
3✔
1423
                return Err(CreateTxError::RbfSequence)
1✔
1424
            }
1425
            // RBF with a specific value requested, but the value is incompatible with CSV
1426
            (Some(tx_builder::RbfValue::Value(rbf)), Some(csv))
1✔
1427
                if !check_nsequence_rbf(rbf, csv) =>
1✔
1428
            {
1✔
1429
                return Err(CreateTxError::RbfSequenceCsv { rbf, csv })
1✔
1430
            }
1431

1432
            // RBF enabled with the default value with CSV also enabled. CSV takes precedence
1433
            (Some(tx_builder::RbfValue::Default), Some(csv)) => csv,
1✔
1434
            // Valid RBF, either default or with a specific value. We ignore the `CSV` value
1435
            // because we've already checked it before
1436
            (Some(rbf), _) => rbf.get_value(),
20✔
1437
        };
1438

1439
        let (fee_rate, mut fee_amount) = match params.fee_policy.unwrap_or_default() {
140✔
1440
            //FIXME: see https://github.com/bitcoindevkit/bdk/issues/256
1441
            FeePolicy::FeeAmount(fee) => {
9✔
1442
                if let Some(previous_fee) = params.bumping_fee {
9✔
1443
                    if fee < previous_fee.absolute {
6✔
1444
                        return Err(CreateTxError::FeeTooLow {
2✔
1445
                            required: Amount::from_sat(previous_fee.absolute),
2✔
1446
                        });
2✔
1447
                    }
4✔
1448
                }
3✔
1449
                (FeeRate::ZERO, fee)
7✔
1450
            }
1451
            FeePolicy::FeeRate(rate) => {
131✔
1452
                if let Some(previous_fee) = params.bumping_fee {
131✔
1453
                    let required_feerate = FeeRate::from_sat_per_kwu(
11✔
1454
                        previous_fee.rate.to_sat_per_kwu()
11✔
1455
                            + FeeRate::BROADCAST_MIN.to_sat_per_kwu(), // +1 sat/vb
11✔
1456
                    );
11✔
1457
                    if rate < required_feerate {
11✔
1458
                        return Err(CreateTxError::FeeRateTooLow {
1✔
1459
                            required: required_feerate,
1✔
1460
                        });
1✔
1461
                    }
10✔
1462
                }
120✔
1463
                (rate, 0)
130✔
1464
            }
1465
        };
1466

1467
        let mut tx = Transaction {
137✔
1468
            version: transaction::Version::non_standard(version),
137✔
1469
            lock_time,
137✔
1470
            input: vec![],
137✔
1471
            output: vec![],
137✔
1472
        };
137✔
1473

137✔
1474
        if params.manually_selected_only && params.utxos.is_empty() {
137✔
1475
            return Err(CreateTxError::NoUtxosSelected);
1✔
1476
        }
136✔
1477

136✔
1478
        let mut outgoing = Amount::ZERO;
136✔
1479
        let mut received = Amount::ZERO;
136✔
1480

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

1483
        for (index, (script_pubkey, value)) in recipients.enumerate() {
136✔
1484
            if !params.allow_dust && value.is_dust(script_pubkey) && !script_pubkey.is_op_return() {
85✔
1485
                return Err(CreateTxError::OutputBelowDustLimit(index));
1✔
1486
            }
84✔
1487

84✔
1488
            if self.is_mine(script_pubkey) {
84✔
1489
                received += Amount::from_sat(value);
42✔
1490
            }
46✔
1491

1492
            let new_out = TxOut {
84✔
1493
                script_pubkey: script_pubkey.clone(),
84✔
1494
                value: Amount::from_sat(value),
84✔
1495
            };
84✔
1496

84✔
1497
            tx.output.push(new_out);
84✔
1498

84✔
1499
            outgoing += Amount::from_sat(value);
84✔
1500
        }
1501

1502
        fee_amount += (fee_rate * tx.weight()).to_sat();
135✔
1503

135✔
1504
        let (required_utxos, optional_utxos) =
135✔
1505
            self.preselect_utxos(&params, Some(current_height.to_consensus_u32()));
135✔
1506

1507
        // get drain script
1508
        let drain_script = match params.drain_to {
135✔
1509
            Some(ref drain_recipient) => drain_recipient.clone(),
53✔
1510
            None => {
1511
                let change_keychain = KeychainKind::Internal;
82✔
1512
                let ((index, spk), index_changeset) = self
82✔
1513
                    .indexed_graph
82✔
1514
                    .index
82✔
1515
                    .next_unused_spk(&change_keychain)
82✔
1516
                    .expect("keychain must exist");
82✔
1517
                let spk = spk.into();
82✔
1518
                self.indexed_graph.index.mark_used(change_keychain, index);
82✔
1519
                self.persist
82✔
1520
                    .stage(ChangeSet::from(indexed_tx_graph::ChangeSet::from(
82✔
1521
                        index_changeset,
82✔
1522
                    )));
82✔
1523
                self.persist.commit().map_err(CreateTxError::Persist)?;
82✔
1524
                spk
82✔
1525
            }
1526
        };
1527

1528
        let (required_utxos, optional_utxos) =
135✔
1529
            coin_selection::filter_duplicates(required_utxos, optional_utxos);
135✔
1530

1531
        let coin_selection = coin_selection.coin_select(
135✔
1532
            required_utxos,
135✔
1533
            optional_utxos,
135✔
1534
            fee_rate,
135✔
1535
            outgoing.to_sat() + fee_amount,
135✔
1536
            &drain_script,
135✔
1537
        )?;
135✔
1538
        fee_amount += coin_selection.fee_amount;
128✔
1539
        let excess = &coin_selection.excess;
128✔
1540

128✔
1541
        tx.input = coin_selection
128✔
1542
            .selected
128✔
1543
            .iter()
128✔
1544
            .map(|u| bitcoin::TxIn {
144✔
1545
                previous_output: u.outpoint(),
144✔
1546
                script_sig: ScriptBuf::default(),
144✔
1547
                sequence: u.sequence().unwrap_or(n_sequence),
144✔
1548
                witness: Witness::new(),
144✔
1549
            })
144✔
1550
            .collect();
128✔
1551

128✔
1552
        if tx.output.is_empty() {
128✔
1553
            // Uh oh, our transaction has no outputs.
1554
            // We allow this when:
1555
            // - We have a drain_to address and the utxos we must spend (this happens,
1556
            // for example, when we RBF)
1557
            // - We have a drain_to address and drain_wallet set
1558
            // Otherwise, we don't know who we should send the funds to, and how much
1559
            // we should send!
1560
            if params.drain_to.is_some() && (params.drain_wallet || !params.utxos.is_empty()) {
51✔
1561
                if let NoChange {
1562
                    dust_threshold,
1✔
1563
                    remaining_amount,
1✔
1564
                    change_fee,
1✔
1565
                } = excess
49✔
1566
                {
1567
                    return Err(CreateTxError::CoinSelection(Error::InsufficientFunds {
1✔
1568
                        needed: *dust_threshold,
1✔
1569
                        available: remaining_amount.saturating_sub(*change_fee),
1✔
1570
                    }));
1✔
1571
                }
48✔
1572
            } else {
1573
                return Err(CreateTxError::NoRecipients);
2✔
1574
            }
1575
        }
77✔
1576

1577
        match excess {
125✔
1578
            NoChange {
1579
                remaining_amount, ..
3✔
1580
            } => fee_amount += remaining_amount,
3✔
1581
            Change { amount, fee } => {
122✔
1582
                if self.is_mine(&drain_script) {
122✔
1583
                    received += Amount::from_sat(*amount);
112✔
1584
                }
112✔
1585
                fee_amount += fee;
122✔
1586

122✔
1587
                // create drain output
122✔
1588
                let drain_output = TxOut {
122✔
1589
                    value: Amount::from_sat(*amount),
122✔
1590
                    script_pubkey: drain_script,
122✔
1591
                };
122✔
1592

122✔
1593
                // TODO: We should pay attention when adding a new output: this might increase
122✔
1594
                // the length of the "number of vouts" parameter by 2 bytes, potentially making
122✔
1595
                // our feerate too low
122✔
1596
                tx.output.push(drain_output);
122✔
1597
            }
1598
        };
1599

1600
        // sort input/outputs according to the chosen algorithm
1601
        params.ordering.sort_tx(&mut tx);
125✔
1602

1603
        let psbt = self.complete_transaction(tx, coin_selection.selected, params)?;
125✔
1604
        Ok(psbt)
123✔
1605
    }
146✔
1606

1607
    /// Bump the fee of a transaction previously created with this wallet.
1608
    ///
1609
    /// Returns an error if the transaction is already confirmed or doesn't explicitly signal
1610
    /// *replace by fee* (RBF). If the transaction can be fee bumped then it returns a [`TxBuilder`]
1611
    /// pre-populated with the inputs and outputs of the original transaction.
1612
    ///
1613
    /// ## Example
1614
    ///
1615
    /// ```no_run
1616
    /// # // TODO: remove norun -- bumping fee seems to need the tx in the wallet database first.
1617
    /// # use std::str::FromStr;
1618
    /// # use bitcoin::*;
1619
    /// # use bdk_wallet::*;
1620
    /// # use bdk_wallet::wallet::ChangeSet;
1621
    /// # use bdk_wallet::wallet::error::CreateTxError;
1622
    /// # use bdk_persist::PersistBackend;
1623
    /// # use anyhow::Error;
1624
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1625
    /// # let mut wallet = doctest_wallet!();
1626
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1627
    /// let mut psbt = {
1628
    ///     let mut builder = wallet.build_tx();
1629
    ///     builder
1630
    ///         .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000))
1631
    ///         .enable_rbf();
1632
    ///     builder.finish()?
1633
    /// };
1634
    /// let _ = wallet.sign(&mut psbt, SignOptions::default())?;
1635
    /// let tx = psbt.clone().extract_tx().expect("tx");
1636
    /// // broadcast tx but it's taking too long to confirm so we want to bump the fee
1637
    /// let mut psbt =  {
1638
    ///     let mut builder = wallet.build_fee_bump(tx.compute_txid())?;
1639
    ///     builder
1640
    ///         .fee_rate(FeeRate::from_sat_per_vb(5).expect("valid feerate"));
1641
    ///     builder.finish()?
1642
    /// };
1643
    ///
1644
    /// let _ = wallet.sign(&mut psbt, SignOptions::default())?;
1645
    /// let fee_bumped_tx = psbt.extract_tx();
1646
    /// // broadcast fee_bumped_tx to replace original
1647
    /// # Ok::<(), anyhow::Error>(())
1648
    /// ```
1649
    // TODO: support for merging multiple transactions while bumping the fees
1650
    pub fn build_fee_bump(
152✔
1651
        &mut self,
152✔
1652
        txid: Txid,
152✔
1653
    ) -> Result<TxBuilder<'_, DefaultCoinSelectionAlgorithm>, BuildFeeBumpError> {
152✔
1654
        let graph = self.indexed_graph.graph();
152✔
1655
        let txout_index = &self.indexed_graph.index;
152✔
1656
        let chain_tip = self.chain.tip().block_id();
152✔
1657

1658
        let mut tx = graph
152✔
1659
            .get_tx(txid)
152✔
1660
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?
152✔
1661
            .as_ref()
152✔
1662
            .clone();
152✔
1663

1664
        let pos = graph
152✔
1665
            .get_chain_position(&self.chain, chain_tip, txid)
152✔
1666
            .ok_or(BuildFeeBumpError::TransactionNotFound(txid))?;
152✔
1667
        if let ChainPosition::Confirmed(_) = pos {
152✔
1668
            return Err(BuildFeeBumpError::TransactionConfirmed(txid));
8✔
1669
        }
144✔
1670

144✔
1671
        if !tx
144✔
1672
            .input
144✔
1673
            .iter()
144✔
1674
            .any(|txin| txin.sequence.to_consensus_u32() <= 0xFFFFFFFD)
144✔
1675
        {
1676
            return Err(BuildFeeBumpError::IrreplaceableTransaction(
8✔
1677
                tx.compute_txid(),
8✔
1678
            ));
8✔
1679
        }
136✔
1680

1681
        let fee = self
136✔
1682
            .calculate_fee(&tx)
136✔
1683
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1684
        let fee_rate = self
136✔
1685
            .calculate_fee_rate(&tx)
136✔
1686
            .map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
136✔
1687

1688
        // remove the inputs from the tx and process them
1689
        let original_txin = tx.input.drain(..).collect::<Vec<_>>();
136✔
1690
        let original_utxos = original_txin
136✔
1691
            .iter()
136✔
1692
            .map(|txin| -> Result<_, BuildFeeBumpError> {
144✔
1693
                let prev_tx = graph
144✔
1694
                    .get_tx(txin.previous_output.txid)
144✔
1695
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?;
144✔
1696
                let txout = &prev_tx.output[txin.previous_output.vout as usize];
144✔
1697

1698
                let confirmation_time: ConfirmationTime = graph
144✔
1699
                    .get_chain_position(&self.chain, chain_tip, txin.previous_output.txid)
144✔
1700
                    .ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?
144✔
1701
                    .cloned()
144✔
1702
                    .into();
144✔
1703

1704
                let weighted_utxo = match txout_index.index_of_spk(&txout.script_pubkey) {
144✔
1705
                    Some((keychain, derivation_index)) => {
144✔
1706
                        // TODO: (@leonardo) remove unwrap() use here, use expect or proper error!
144✔
1707
                        let satisfaction_weight = self
144✔
1708
                            .get_descriptor_for_keychain(keychain)
144✔
1709
                            .max_weight_to_satisfy()
144✔
1710
                            .unwrap();
144✔
1711
                        WeightedUtxo {
144✔
1712
                            utxo: Utxo::Local(LocalOutput {
144✔
1713
                                outpoint: txin.previous_output,
144✔
1714
                                txout: txout.clone(),
144✔
1715
                                keychain,
144✔
1716
                                is_spent: true,
144✔
1717
                                derivation_index,
144✔
1718
                                confirmation_time,
144✔
1719
                            }),
144✔
1720
                            satisfaction_weight,
144✔
1721
                        }
144✔
1722
                    }
1723
                    None => {
NEW
1724
                        let satisfaction_weight = Weight::from_wu_usize(
×
NEW
1725
                            serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len(),
×
NEW
1726
                        );
×
1727
                        WeightedUtxo {
×
1728
                            utxo: Utxo::Foreign {
×
1729
                                outpoint: txin.previous_output,
×
1730
                                sequence: Some(txin.sequence),
×
1731
                                psbt_input: Box::new(psbt::Input {
×
1732
                                    witness_utxo: Some(txout.clone()),
×
1733
                                    non_witness_utxo: Some(prev_tx.as_ref().clone()),
×
1734
                                    ..Default::default()
×
1735
                                }),
×
1736
                            },
×
1737
                            satisfaction_weight,
×
1738
                        }
×
1739
                    }
1740
                };
1741

1742
                Ok(weighted_utxo)
144✔
1743
            })
144✔
1744
            .collect::<Result<Vec<_>, _>>()?;
136✔
1745

1746
        if tx.output.len() > 1 {
136✔
1747
            let mut change_index = None;
80✔
1748
            for (index, txout) in tx.output.iter().enumerate() {
160✔
1749
                let change_keychain = KeychainKind::Internal;
160✔
1750
                match txout_index.index_of_spk(&txout.script_pubkey) {
160✔
1751
                    Some((keychain, _)) if keychain == change_keychain => {
104✔
1752
                        change_index = Some(index)
80✔
1753
                    }
1754
                    _ => {}
80✔
1755
                }
1756
            }
1757

1758
            if let Some(change_index) = change_index {
80✔
1759
                tx.output.remove(change_index);
80✔
1760
            }
80✔
1761
        }
56✔
1762

1763
        let params = TxParams {
136✔
1764
            // TODO: figure out what rbf option should be?
136✔
1765
            version: Some(tx_builder::Version(tx.version.0)),
136✔
1766
            recipients: tx
136✔
1767
                .output
136✔
1768
                .into_iter()
136✔
1769
                .map(|txout| (txout.script_pubkey, txout.value.to_sat()))
136✔
1770
                .collect(),
136✔
1771
            utxos: original_utxos,
136✔
1772
            bumping_fee: Some(tx_builder::PreviousFee {
136✔
1773
                absolute: fee.to_sat(),
136✔
1774
                rate: fee_rate,
136✔
1775
            }),
136✔
1776
            ..Default::default()
136✔
1777
        };
136✔
1778

136✔
1779
        Ok(TxBuilder {
136✔
1780
            wallet: alloc::rc::Rc::new(core::cell::RefCell::new(self)),
136✔
1781
            params,
136✔
1782
            coin_selection: DefaultCoinSelectionAlgorithm::default(),
136✔
1783
        })
136✔
1784
    }
152✔
1785

1786
    /// Sign a transaction with all the wallet's signers, in the order specified by every signer's
1787
    /// [`SignerOrdering`]. This function returns the `Result` type with an encapsulated `bool` that has the value true if the PSBT was finalized, or false otherwise.
1788
    ///
1789
    /// The [`SignOptions`] can be used to tweak the behavior of the software signers, and the way
1790
    /// the transaction is finalized at the end. Note that it can't be guaranteed that *every*
1791
    /// signers will follow the options, but the "software signers" (WIF keys and `xprv`) defined
1792
    /// in this library will.
1793
    ///
1794
    /// ## Example
1795
    ///
1796
    /// ```
1797
    /// # use std::str::FromStr;
1798
    /// # use bitcoin::*;
1799
    /// # use bdk_wallet::*;
1800
    /// # use bdk_wallet::wallet::ChangeSet;
1801
    /// # use bdk_wallet::wallet::error::CreateTxError;
1802
    /// # use bdk_persist::PersistBackend;
1803
    /// # let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
1804
    /// # let mut wallet = doctest_wallet!();
1805
    /// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
1806
    /// let mut psbt = {
1807
    ///     let mut builder = wallet.build_tx();
1808
    ///     builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
1809
    ///     builder.finish()?
1810
    /// };
1811
    /// let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
1812
    /// assert!(finalized, "we should have signed all the inputs");
1813
    /// # Ok::<(),anyhow::Error>(())
1814
    pub fn sign(&self, psbt: &mut Psbt, sign_options: SignOptions) -> Result<bool, SignerError> {
336✔
1815
        // This adds all the PSBT metadata for the inputs, which will help us later figure out how
336✔
1816
        // to derive our keys
336✔
1817
        self.update_psbt_with_descriptor(psbt)
336✔
1818
            .map_err(SignerError::MiniscriptPsbt)?;
336✔
1819

1820
        // If we aren't allowed to use `witness_utxo`, ensure that every input (except p2tr and finalized ones)
1821
        // has the `non_witness_utxo`
1822
        if !sign_options.trust_witness_utxo
336✔
1823
            && psbt
288✔
1824
                .inputs
288✔
1825
                .iter()
288✔
1826
                .filter(|i| i.final_script_witness.is_none() && i.final_script_sig.is_none())
296✔
1827
                .filter(|i| i.tap_internal_key.is_none() && i.tap_merkle_root.is_none())
288✔
1828
                .any(|i| i.non_witness_utxo.is_none())
288✔
1829
        {
1830
            return Err(SignerError::MissingNonWitnessUtxo);
×
1831
        }
336✔
1832

336✔
1833
        // If the user hasn't explicitly opted-in, refuse to sign the transaction unless every input
336✔
1834
        // is using `SIGHASH_ALL` or `SIGHASH_DEFAULT` for taproot
336✔
1835
        if !sign_options.allow_all_sighashes
336✔
1836
            && !psbt.inputs.iter().all(|i| {
344✔
1837
                i.sighash_type.is_none()
344✔
1838
                    || i.sighash_type == Some(EcdsaSighashType::All.into())
24✔
1839
                    || i.sighash_type == Some(TapSighashType::All.into())
16✔
1840
                    || i.sighash_type == Some(TapSighashType::Default.into())
16✔
1841
            })
344✔
1842
        {
1843
            return Err(SignerError::NonStandardSighash);
16✔
1844
        }
320✔
1845

1846
        for signer in self
664✔
1847
            .signers
320✔
1848
            .signers()
320✔
1849
            .iter()
320✔
1850
            .chain(self.change_signers.signers().iter())
320✔
1851
        {
1852
            signer.sign_transaction(psbt, &sign_options, &self.secp)?;
664✔
1853
        }
1854

1855
        // attempt to finalize
1856
        if sign_options.try_finalize {
288✔
1857
            self.finalize_psbt(psbt, sign_options)
272✔
1858
        } else {
1859
            Ok(false)
16✔
1860
        }
1861
    }
336✔
1862

1863
    /// Return the spending policies for the wallet's descriptor
1864
    pub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, DescriptorError> {
24✔
1865
        let signers = match keychain {
24✔
1866
            KeychainKind::External => &self.signers,
24✔
1867
            KeychainKind::Internal => &self.change_signers,
×
1868
        };
1869

1870
        self.public_descriptor(keychain).extract_policy(
24✔
1871
            signers,
24✔
1872
            BuildSatisfaction::None,
24✔
1873
            &self.secp,
24✔
1874
        )
24✔
1875
    }
24✔
1876

1877
    /// Return the "public" version of the wallet's descriptor, meaning a new descriptor that has
1878
    /// the same structure but with every secret key removed
1879
    ///
1880
    /// This can be used to build a watch-only version of a wallet
1881
    pub fn public_descriptor(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,252✔
1882
        self.indexed_graph
6,252✔
1883
            .index
6,252✔
1884
            .keychains()
6,252✔
1885
            .find(|(k, _)| *k == &keychain)
7,082✔
1886
            .map(|(_, d)| d)
6,252✔
1887
            .expect("keychain must exist")
6,252✔
1888
    }
6,252✔
1889

1890
    /// Finalize a PSBT, i.e., for each input determine if sufficient data is available to pass
1891
    /// validation and construct the respective `scriptSig` or `scriptWitness`. Please refer to
1892
    /// [BIP174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#Input_Finalizer)
1893
    /// for further information.
1894
    ///
1895
    /// Returns `true` if the PSBT could be finalized, and `false` otherwise.
1896
    ///
1897
    /// The [`SignOptions`] can be used to tweak the behavior of the finalizer.
1898
    pub fn finalize_psbt(
272✔
1899
        &self,
272✔
1900
        psbt: &mut Psbt,
272✔
1901
        sign_options: SignOptions,
272✔
1902
    ) -> Result<bool, SignerError> {
272✔
1903
        let chain_tip = self.chain.tip().block_id();
272✔
1904

272✔
1905
        let tx = &psbt.unsigned_tx;
272✔
1906
        let mut finished = true;
272✔
1907

1908
        for (n, input) in tx.input.iter().enumerate() {
312✔
1909
            let psbt_input = &psbt
312✔
1910
                .inputs
312✔
1911
                .get(n)
312✔
1912
                .ok_or(SignerError::InputIndexOutOfRange)?;
312✔
1913
            if psbt_input.final_script_sig.is_some() || psbt_input.final_script_witness.is_some() {
304✔
1914
                continue;
16✔
1915
            }
288✔
1916
            let confirmation_height = self
288✔
1917
                .indexed_graph
288✔
1918
                .graph()
288✔
1919
                .get_chain_position(&self.chain, chain_tip, input.previous_output.txid)
288✔
1920
                .map(|chain_position| match chain_position {
288✔
1921
                    ChainPosition::Confirmed(a) => a.confirmation_height,
264✔
1922
                    ChainPosition::Unconfirmed(_) => u32::MAX,
×
1923
                });
288✔
1924
            let current_height = sign_options
288✔
1925
                .assume_height
288✔
1926
                .unwrap_or_else(|| self.chain.tip().height());
288✔
1927

288✔
1928
            // - Try to derive the descriptor by looking at the txout. If it's in our database, we
288✔
1929
            //   know exactly which `keychain` to use, and which derivation index it is
288✔
1930
            // - If that fails, try to derive it by looking at the psbt input: the complete logic
288✔
1931
            //   is in `src/descriptor/mod.rs`, but it will basically look at `bip32_derivation`,
288✔
1932
            //   `redeem_script` and `witness_script` to determine the right derivation
288✔
1933
            // - If that also fails, it will try it on the internal descriptor, if present
288✔
1934
            let desc = psbt
288✔
1935
                .get_utxo_for(n)
288✔
1936
                .and_then(|txout| self.get_descriptor_for_txout(&txout))
288✔
1937
                .or_else(|| {
288✔
1938
                    self.indexed_graph.index.keychains().find_map(|(_, desc)| {
32✔
1939
                        desc.derive_from_psbt_input(psbt_input, psbt.get_utxo_for(n), &self.secp)
32✔
1940
                    })
32✔
1941
                });
288✔
1942

288✔
1943
            match desc {
288✔
1944
                Some(desc) => {
272✔
1945
                    let mut tmp_input = bitcoin::TxIn::default();
272✔
1946
                    match desc.satisfy(
272✔
1947
                        &mut tmp_input,
272✔
1948
                        (
272✔
1949
                            PsbtInputSatisfier::new(psbt, n),
272✔
1950
                            After::new(Some(current_height), false),
272✔
1951
                            Older::new(Some(current_height), confirmation_height, false),
272✔
1952
                        ),
272✔
1953
                    ) {
272✔
1954
                        Ok(_) => {
1955
                            let psbt_input = &mut psbt.inputs[n];
264✔
1956
                            psbt_input.final_script_sig = Some(tmp_input.script_sig);
264✔
1957
                            psbt_input.final_script_witness = Some(tmp_input.witness);
264✔
1958
                            if sign_options.remove_partial_sigs {
264✔
1959
                                psbt_input.partial_sigs.clear();
240✔
1960
                            }
240✔
1961
                            if sign_options.remove_taproot_extras {
264✔
1962
                                // We just constructed the final witness, clear these fields.
264✔
1963
                                psbt_input.tap_key_sig = None;
264✔
1964
                                psbt_input.tap_script_sigs.clear();
264✔
1965
                                psbt_input.tap_scripts.clear();
264✔
1966
                                psbt_input.tap_key_origins.clear();
264✔
1967
                                psbt_input.tap_internal_key = None;
264✔
1968
                                psbt_input.tap_merkle_root = None;
264✔
1969
                            }
264✔
1970
                        }
1971
                        Err(_) => finished = false,
8✔
1972
                    }
1973
                }
1974
                None => finished = false,
16✔
1975
            }
1976
        }
1977

1978
        if finished && sign_options.remove_taproot_extras {
264✔
1979
            for output in &mut psbt.outputs {
568✔
1980
                output.tap_key_origins.clear();
328✔
1981
            }
328✔
1982
        }
24✔
1983

1984
        Ok(finished)
264✔
1985
    }
272✔
1986

1987
    /// Return the secp256k1 context used for all signing operations
1988
    pub fn secp_ctx(&self) -> &SecpCtx {
28✔
1989
        &self.secp
28✔
1990
    }
28✔
1991

1992
    /// Returns the descriptor used to create addresses for a particular `keychain`.
1993
    pub fn get_descriptor_for_keychain(&self, keychain: KeychainKind) -> &ExtendedDescriptor {
6,084✔
1994
        self.public_descriptor(keychain)
6,084✔
1995
    }
6,084✔
1996

1997
    /// The derivation index of this wallet. It will return `None` if it has not derived any addresses.
1998
    /// Otherwise, it will return the index of the highest address it has derived.
1999
    pub fn derivation_index(&self, keychain: KeychainKind) -> Option<u32> {
40✔
2000
        self.indexed_graph.index.last_revealed_index(&keychain)
40✔
2001
    }
40✔
2002

2003
    /// The index of the next address that you would get if you were to ask the wallet for a new address
2004
    pub fn next_derivation_index(&self, keychain: KeychainKind) -> u32 {
×
2005
        self.indexed_graph
×
2006
            .index
×
2007
            .next_index(&keychain)
×
2008
            .expect("keychain must exist")
×
2009
            .0
×
2010
    }
×
2011

2012
    /// Informs the wallet that you no longer intend to broadcast a tx that was built from it.
2013
    ///
2014
    /// This frees up the change address used when creating the tx for use in future transactions.
2015
    // TODO: Make this free up reserved utxos when that's implemented
2016
    pub fn cancel_tx(&mut self, tx: &Transaction) {
16✔
2017
        let txout_index = &mut self.indexed_graph.index;
16✔
2018
        for txout in &tx.output {
48✔
2019
            if let Some((keychain, index)) = txout_index.index_of_spk(&txout.script_pubkey) {
32✔
2020
                // NOTE: unmark_used will **not** make something unused if it has actually been used
16✔
2021
                // by a tx in the tracker. It only removes the superficial marking.
16✔
2022
                txout_index.unmark_used(keychain, index);
16✔
2023
            }
16✔
2024
        }
2025
    }
16✔
2026

2027
    fn get_descriptor_for_txout(&self, txout: &TxOut) -> Option<DerivedDescriptor> {
288✔
2028
        let (keychain, child) = self
288✔
2029
            .indexed_graph
288✔
2030
            .index
288✔
2031
            .index_of_spk(&txout.script_pubkey)?;
288✔
2032
        let descriptor = self.get_descriptor_for_keychain(keychain);
272✔
2033
        descriptor.at_derivation_index(child).ok()
272✔
2034
    }
288✔
2035

2036
    fn get_available_utxos(&self) -> Vec<(LocalOutput, Weight)> {
1,136✔
2037
        self.list_unspent()
1,136✔
2038
            .map(|utxo| {
1,248✔
2039
                let keychain = utxo.keychain;
1,248✔
2040
                (utxo, {
1,248✔
2041
                    self.get_descriptor_for_keychain(keychain)
1,248✔
2042
                        .max_weight_to_satisfy()
1,248✔
2043
                        .unwrap() // TODO: (@leonardo) remove unwrap() use here, use expect or proper error!
1,248✔
2044
                })
1,248✔
2045
            })
1,248✔
2046
            .collect()
1,136✔
2047
    }
1,136✔
2048

2049
    /// Given the options returns the list of utxos that must be used to form the
2050
    /// transaction and any further that may be used if needed.
2051
    fn preselect_utxos(
1,136✔
2052
        &self,
1,136✔
2053
        params: &TxParams,
1,136✔
2054
        current_height: Option<u32>,
1,136✔
2055
    ) -> (Vec<WeightedUtxo>, Vec<WeightedUtxo>) {
1,136✔
2056
        let TxParams {
1,136✔
2057
            change_policy,
1,136✔
2058
            unspendable,
1,136✔
2059
            utxos,
1,136✔
2060
            drain_wallet,
1,136✔
2061
            manually_selected_only,
1,136✔
2062
            bumping_fee,
1,136✔
2063
            ..
1,136✔
2064
        } = params;
1,136✔
2065

1,136✔
2066
        let manually_selected = utxos.clone();
1,136✔
2067
        // we mandate confirmed transactions if we're bumping the fee
1,136✔
2068
        let must_only_use_confirmed_tx = bumping_fee.is_some();
1,136✔
2069
        let must_use_all_available = *drain_wallet;
1,136✔
2070

1,136✔
2071
        let chain_tip = self.chain.tip().block_id();
1,136✔
2072
        //    must_spend <- manually selected utxos
1,136✔
2073
        //    may_spend  <- all other available utxos
1,136✔
2074
        let mut may_spend = self.get_available_utxos();
1,136✔
2075

1,136✔
2076
        may_spend.retain(|may_spend| {
1,248✔
2077
            !manually_selected
1,248✔
2078
                .iter()
1,248✔
2079
                .any(|manually_selected| manually_selected.utxo.outpoint() == may_spend.0.outpoint)
1,248✔
2080
        });
1,248✔
2081
        let mut must_spend = manually_selected;
1,136✔
2082

1,136✔
2083
        // NOTE: we are intentionally ignoring `unspendable` here. i.e manual
1,136✔
2084
        // selection overrides unspendable.
1,136✔
2085
        if *manually_selected_only {
1,136✔
2086
            return (must_spend, vec![]);
40✔
2087
        }
1,096✔
2088

1,096✔
2089
        let satisfies_confirmed = may_spend
1,096✔
2090
            .iter()
1,096✔
2091
            .map(|u| -> bool {
1,136✔
2092
                let txid = u.0.outpoint.txid;
1,136✔
2093
                let tx = match self.indexed_graph.graph().get_tx(txid) {
1,136✔
2094
                    Some(tx) => tx,
1,136✔
2095
                    None => return false,
×
2096
                };
2097
                let confirmation_time: ConfirmationTime = match self
1,136✔
2098
                    .indexed_graph
1,136✔
2099
                    .graph()
1,136✔
2100
                    .get_chain_position(&self.chain, chain_tip, txid)
1,136✔
2101
                {
2102
                    Some(chain_position) => chain_position.cloned().into(),
1,136✔
2103
                    None => return false,
×
2104
                };
2105

2106
                // Whether the UTXO is mature and, if needed, confirmed
2107
                let mut spendable = true;
1,136✔
2108
                if must_only_use_confirmed_tx && !confirmation_time.is_confirmed() {
1,136✔
2109
                    return false;
64✔
2110
                }
1,072✔
2111
                if tx.is_coinbase() {
1,072✔
2112
                    debug_assert!(
24✔
2113
                        confirmation_time.is_confirmed(),
24✔
2114
                        "coinbase must always be confirmed"
×
2115
                    );
2116
                    if let Some(current_height) = current_height {
24✔
2117
                        match confirmation_time {
24✔
2118
                            ConfirmationTime::Confirmed { height, .. } => {
24✔
2119
                                // https://github.com/bitcoin/bitcoin/blob/c5e67be03bb06a5d7885c55db1f016fbf2333fe3/src/validation.cpp#L373-L375
24✔
2120
                                spendable &=
24✔
2121
                                    (current_height.saturating_sub(height)) >= COINBASE_MATURITY;
24✔
2122
                            }
24✔
2123
                            ConfirmationTime::Unconfirmed { .. } => spendable = false,
×
2124
                        }
2125
                    }
×
2126
                }
1,048✔
2127
                spendable
1,072✔
2128
            })
1,136✔
2129
            .collect::<Vec<_>>();
1,096✔
2130

1,096✔
2131
        let mut i = 0;
1,096✔
2132
        may_spend.retain(|u| {
1,136✔
2133
            let retain = change_policy.is_satisfied_by(&u.0)
1,136✔
2134
                && !unspendable.contains(&u.0.outpoint)
1,128✔
2135
                && satisfies_confirmed[i];
1,128✔
2136
            i += 1;
1,136✔
2137
            retain
1,136✔
2138
        });
1,136✔
2139

1,096✔
2140
        let mut may_spend = may_spend
1,096✔
2141
            .into_iter()
1,096✔
2142
            .map(|(local_utxo, satisfaction_weight)| WeightedUtxo {
1,096✔
2143
                satisfaction_weight,
1,048✔
2144
                utxo: Utxo::Local(local_utxo),
1,048✔
2145
            })
1,096✔
2146
            .collect();
1,096✔
2147

1,096✔
2148
        if must_use_all_available {
1,096✔
2149
            must_spend.append(&mut may_spend);
400✔
2150
        }
696✔
2151

2152
        (must_spend, may_spend)
1,096✔
2153
    }
1,136✔
2154

2155
    fn complete_transaction(
1,056✔
2156
        &self,
1,056✔
2157
        tx: Transaction,
1,056✔
2158
        selected: Vec<Utxo>,
1,056✔
2159
        params: TxParams,
1,056✔
2160
    ) -> Result<Psbt, CreateTxError> {
1,056✔
2161
        let mut psbt = Psbt::from_unsigned_tx(tx)?;
1,056✔
2162

2163
        if params.add_global_xpubs {
1,056✔
2164
            let all_xpubs = self
24✔
2165
                .keychains()
24✔
2166
                .flat_map(|(_, desc)| desc.get_extended_keys())
48✔
2167
                .collect::<Vec<_>>();
24✔
2168

2169
            for xpub in all_xpubs {
56✔
2170
                let origin = match xpub.origin {
32✔
2171
                    Some(origin) => origin,
24✔
2172
                    None if xpub.xkey.depth == 0 => {
16✔
2173
                        (xpub.root_fingerprint(&self.secp), vec![].into())
8✔
2174
                    }
2175
                    _ => return Err(CreateTxError::MissingKeyOrigin(xpub.xkey.to_string())),
8✔
2176
                };
2177

2178
                psbt.xpub.insert(xpub.xkey, origin);
32✔
2179
            }
2180
        }
1,032✔
2181

2182
        let mut lookup_output = selected
1,048✔
2183
            .into_iter()
1,048✔
2184
            .map(|utxo| (utxo.outpoint(), utxo))
1,176✔
2185
            .collect::<HashMap<_, _>>();
1,048✔
2186

2187
        // add metadata for the inputs
2188
        for (psbt_input, input) in psbt.inputs.iter_mut().zip(psbt.unsigned_tx.input.iter()) {
1,176✔
2189
            let utxo = match lookup_output.remove(&input.previous_output) {
1,176✔
2190
                Some(utxo) => utxo,
1,176✔
2191
                None => continue,
×
2192
            };
2193

2194
            match utxo {
1,176✔
2195
                Utxo::Local(utxo) => {
1,128✔
2196
                    *psbt_input =
1,128✔
2197
                        match self.get_psbt_input(utxo, params.sighash, params.only_witness_utxo) {
1,128✔
2198
                            Ok(psbt_input) => psbt_input,
1,128✔
2199
                            Err(e) => match e {
×
2200
                                CreateTxError::UnknownUtxo => psbt::Input {
×
2201
                                    sighash_type: params.sighash,
×
2202
                                    ..psbt::Input::default()
×
2203
                                },
×
2204
                                _ => return Err(e),
×
2205
                            },
2206
                        }
2207
                }
2208
                Utxo::Foreign {
2209
                    outpoint,
48✔
2210
                    psbt_input: foreign_psbt_input,
48✔
2211
                    ..
48✔
2212
                } => {
48✔
2213
                    let is_taproot = foreign_psbt_input
48✔
2214
                        .witness_utxo
48✔
2215
                        .as_ref()
48✔
2216
                        .map(|txout| txout.script_pubkey.is_p2tr())
48✔
2217
                        .unwrap_or(false);
48✔
2218
                    if !is_taproot
48✔
2219
                        && !params.only_witness_utxo
40✔
2220
                        && foreign_psbt_input.non_witness_utxo.is_none()
16✔
2221
                    {
2222
                        return Err(CreateTxError::MissingNonWitnessUtxo(outpoint));
8✔
2223
                    }
40✔
2224
                    *psbt_input = *foreign_psbt_input;
40✔
2225
                }
2226
            }
2227
        }
2228

2229
        self.update_psbt_with_descriptor(&mut psbt)?;
1,040✔
2230

2231
        Ok(psbt)
1,040✔
2232
    }
1,056✔
2233

2234
    /// get the corresponding PSBT Input for a LocalUtxo
2235
    pub fn get_psbt_input(
1,144✔
2236
        &self,
1,144✔
2237
        utxo: LocalOutput,
1,144✔
2238
        sighash_type: Option<psbt::PsbtSighashType>,
1,144✔
2239
        only_witness_utxo: bool,
1,144✔
2240
    ) -> Result<psbt::Input, CreateTxError> {
1,144✔
2241
        // Try to find the prev_script in our db to figure out if this is internal or external,
2242
        // and the derivation index
2243
        let (keychain, child) = self
1,144✔
2244
            .indexed_graph
1,144✔
2245
            .index
1,144✔
2246
            .index_of_spk(&utxo.txout.script_pubkey)
1,144✔
2247
            .ok_or(CreateTxError::UnknownUtxo)?;
1,144✔
2248

2249
        let mut psbt_input = psbt::Input {
1,144✔
2250
            sighash_type,
1,144✔
2251
            ..psbt::Input::default()
1,144✔
2252
        };
1,144✔
2253

1,144✔
2254
        let desc = self.get_descriptor_for_keychain(keychain);
1,144✔
2255
        let derived_descriptor = desc
1,144✔
2256
            .at_derivation_index(child)
1,144✔
2257
            .expect("child can't be hardened");
1,144✔
2258

1,144✔
2259
        psbt_input
1,144✔
2260
            .update_with_descriptor_unchecked(&derived_descriptor)
1,144✔
2261
            .map_err(MiniscriptPsbtError::Conversion)?;
1,144✔
2262

2263
        let prev_output = utxo.outpoint;
1,144✔
2264
        if let Some(prev_tx) = self.indexed_graph.graph().get_tx(prev_output.txid) {
1,144✔
2265
            if desc.is_witness() || desc.is_taproot() {
1,144✔
2266
                psbt_input.witness_utxo = Some(prev_tx.output[prev_output.vout as usize].clone());
1,112✔
2267
            }
1,112✔
2268
            if !desc.is_taproot() && (!desc.is_witness() || !only_witness_utxo) {
1,144✔
2269
                psbt_input.non_witness_utxo = Some(prev_tx.as_ref().clone());
912✔
2270
            }
912✔
2271
        }
×
2272
        Ok(psbt_input)
1,144✔
2273
    }
1,144✔
2274

2275
    fn update_psbt_with_descriptor(&self, psbt: &mut Psbt) -> Result<(), MiniscriptPsbtError> {
1,376✔
2276
        // We need to borrow `psbt` mutably within the loops, so we have to allocate a vec for all
1,376✔
2277
        // the input utxos and outputs
1,376✔
2278
        let utxos = (0..psbt.inputs.len())
1,376✔
2279
            .filter_map(|i| psbt.get_utxo_for(i).map(|utxo| (true, i, utxo)))
1,544✔
2280
            .chain(
1,376✔
2281
                psbt.unsigned_tx
1,376✔
2282
                    .output
1,376✔
2283
                    .iter()
1,376✔
2284
                    .enumerate()
1,376✔
2285
                    .map(|(i, out)| (false, i, out.clone())),
2,168✔
2286
            )
1,376✔
2287
            .collect::<Vec<_>>();
1,376✔
2288

2289
        // Try to figure out the keychain and derivation for every input and output
2290
        for (is_input, index, out) in utxos.into_iter() {
3,672✔
2291
            if let Some((keychain, child)) =
3,104✔
2292
                self.indexed_graph.index.index_of_spk(&out.script_pubkey)
3,672✔
2293
            {
2294
                let desc = self.get_descriptor_for_keychain(keychain);
3,104✔
2295
                let desc = desc
3,104✔
2296
                    .at_derivation_index(child)
3,104✔
2297
                    .expect("child can't be hardened");
3,104✔
2298

3,104✔
2299
                if is_input {
3,104✔
2300
                    psbt.update_input_with_descriptor(index, &desc)
1,432✔
2301
                        .map_err(MiniscriptPsbtError::UtxoUpdate)?;
1,432✔
2302
                } else {
2303
                    psbt.update_output_with_descriptor(index, &desc)
1,672✔
2304
                        .map_err(MiniscriptPsbtError::OutputUpdate)?;
1,672✔
2305
                }
2306
            }
568✔
2307
        }
2308

2309
        Ok(())
1,376✔
2310
    }
1,376✔
2311

2312
    /// Return the checksum of the public descriptor associated to `keychain`
2313
    ///
2314
    /// Internally calls [`Self::get_descriptor_for_keychain`] to fetch the right descriptor
2315
    pub fn descriptor_checksum(&self, keychain: KeychainKind) -> String {
8✔
2316
        self.get_descriptor_for_keychain(keychain)
8✔
2317
            .to_string()
8✔
2318
            .split_once('#')
8✔
2319
            .unwrap()
8✔
2320
            .1
8✔
2321
            .to_string()
8✔
2322
    }
8✔
2323

2324
    /// Applies an update to the wallet and stages the changes (but does not [`commit`] them).
2325
    ///
2326
    /// Usually you create an `update` by interacting with some blockchain data source and inserting
2327
    /// transactions related to your wallet into it.
2328
    ///
2329
    /// [`commit`]: Self::commit
2330
    pub fn apply_update(&mut self, update: impl Into<Update>) -> Result<(), CannotConnectError> {
×
2331
        let update = update.into();
×
2332
        let mut changeset = match update.chain {
×
2333
            Some(chain_update) => ChangeSet::from(self.chain.apply_update(chain_update)?),
×
2334
            None => ChangeSet::default(),
×
2335
        };
2336

2337
        let (_, index_changeset) = self
×
2338
            .indexed_graph
×
2339
            .index
×
2340
            .reveal_to_target_multi(&update.last_active_indices);
×
2341
        changeset.append(ChangeSet::from(indexed_tx_graph::ChangeSet::from(
×
2342
            index_changeset,
×
2343
        )));
×
2344
        changeset.append(ChangeSet::from(
×
2345
            self.indexed_graph.apply_update(update.graph),
×
2346
        ));
×
2347
        self.persist.stage(changeset);
×
2348
        Ok(())
×
2349
    }
×
2350

2351
    /// Commits all currently [`staged`] changed to the persistence backend returning and error when
2352
    /// this fails.
2353
    ///
2354
    /// This returns whether the `update` resulted in any changes.
2355
    ///
2356
    /// [`staged`]: Self::staged
2357
    pub fn commit(&mut self) -> anyhow::Result<bool> {
×
2358
        self.persist.commit().map(|c| c.is_some())
×
2359
    }
×
2360

2361
    /// Returns the changes that will be committed with the next call to [`commit`].
2362
    ///
2363
    /// [`commit`]: Self::commit
2364
    pub fn staged(&self) -> &ChangeSet {
×
2365
        self.persist.staged()
×
2366
    }
×
2367

2368
    /// Get a reference to the inner [`TxGraph`].
2369
    pub fn tx_graph(&self) -> &TxGraph<ConfirmationTimeHeightAnchor> {
×
2370
        self.indexed_graph.graph()
×
2371
    }
×
2372

2373
    /// Get a reference to the inner [`KeychainTxOutIndex`].
2374
    pub fn spk_index(&self) -> &KeychainTxOutIndex<KeychainKind> {
48✔
2375
        &self.indexed_graph.index
48✔
2376
    }
48✔
2377

2378
    /// Get a reference to the inner [`LocalChain`].
2379
    pub fn local_chain(&self) -> &LocalChain {
×
2380
        &self.chain
×
2381
    }
×
2382

2383
    /// Introduces a `block` of `height` to the wallet, and tries to connect it to the
2384
    /// `prev_blockhash` of the block's header.
2385
    ///
2386
    /// This is a convenience method that is equivalent to calling [`apply_block_connected_to`]
2387
    /// with `prev_blockhash` and `height-1` as the `connected_to` parameter.
2388
    ///
2389
    /// [`apply_block_connected_to`]: Self::apply_block_connected_to
2390
    pub fn apply_block(&mut self, block: &Block, height: u32) -> Result<(), CannotConnectError> {
×
2391
        let connected_to = match height.checked_sub(1) {
×
2392
            Some(prev_height) => BlockId {
×
2393
                height: prev_height,
×
2394
                hash: block.header.prev_blockhash,
×
2395
            },
×
2396
            None => BlockId {
×
2397
                height,
×
2398
                hash: block.block_hash(),
×
2399
            },
×
2400
        };
2401
        self.apply_block_connected_to(block, height, connected_to)
×
2402
            .map_err(|err| match err {
×
2403
                ApplyHeaderError::InconsistentBlocks => {
2404
                    unreachable!("connected_to is derived from the block so must be consistent")
×
2405
                }
2406
                ApplyHeaderError::CannotConnect(err) => err,
×
2407
            })
×
2408
    }
×
2409

2410
    /// Applies relevant transactions from `block` of `height` to the wallet, and connects the
2411
    /// block to the internal chain.
2412
    ///
2413
    /// The `connected_to` parameter informs the wallet how this block connects to the internal
2414
    /// [`LocalChain`]. Relevant transactions are filtered from the `block` and inserted into the
2415
    /// internal [`TxGraph`].
2416
    pub fn apply_block_connected_to(
×
2417
        &mut self,
×
2418
        block: &Block,
×
2419
        height: u32,
×
2420
        connected_to: BlockId,
×
2421
    ) -> Result<(), ApplyHeaderError> {
×
2422
        let mut changeset = ChangeSet::default();
×
2423
        changeset.append(
×
2424
            self.chain
×
2425
                .apply_header_connected_to(&block.header, height, connected_to)?
×
2426
                .into(),
×
2427
        );
×
2428
        changeset.append(
×
2429
            self.indexed_graph
×
2430
                .apply_block_relevant(block, height)
×
2431
                .into(),
×
2432
        );
×
2433
        self.persist.stage(changeset);
×
2434
        Ok(())
×
2435
    }
×
2436

2437
    /// Apply relevant unconfirmed transactions to the wallet.
2438
    ///
2439
    /// Transactions that are not relevant are filtered out.
2440
    ///
2441
    /// This method takes in an iterator of `(tx, last_seen)` where `last_seen` is the timestamp of
2442
    /// when the transaction was last seen in the mempool. This is used for conflict resolution
2443
    /// when there is conflicting unconfirmed transactions. The transaction with the later
2444
    /// `last_seen` is prioritized.
2445
    pub fn apply_unconfirmed_txs<'t>(
×
2446
        &mut self,
×
2447
        unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>,
×
2448
    ) {
×
2449
        let indexed_graph_changeset = self
×
2450
            .indexed_graph
×
2451
            .batch_insert_relevant_unconfirmed(unconfirmed_txs);
×
2452
        self.persist.stage(ChangeSet::from(indexed_graph_changeset));
×
2453
    }
×
2454
}
2455

2456
/// Methods to construct sync/full-scan requests for spk-based chain sources.
2457
impl Wallet {
2458
    /// Create a partial [`SyncRequest`] for this wallet for all revealed spks.
2459
    ///
2460
    /// This is the first step when performing a spk-based wallet partial sync, the returned
2461
    /// [`SyncRequest`] collects all revealed script pubkeys from the wallet keychain needed to
2462
    /// start a blockchain sync with a spk based blockchain client.
2463
    pub fn start_sync_with_revealed_spks(&self) -> SyncRequest {
×
2464
        SyncRequest::from_chain_tip(self.chain.tip())
×
2465
            .populate_with_revealed_spks(&self.indexed_graph.index, ..)
×
2466
    }
×
2467

2468
    /// Create a [`FullScanRequest] for this wallet.
2469
    ///
2470
    /// This is the first step when performing a spk-based wallet full scan, the returned
2471
    /// [`FullScanRequest] collects iterators for the wallet's keychain script pub keys needed to
2472
    /// start a blockchain full scan with a spk based blockchain client.
2473
    ///
2474
    /// This operation is generally only used when importing or restoring a previously used wallet
2475
    /// in which the list of used scripts is not known.
2476
    pub fn start_full_scan(&self) -> FullScanRequest<KeychainKind> {
×
2477
        FullScanRequest::from_keychain_txout_index(self.chain.tip(), &self.indexed_graph.index)
×
2478
    }
×
2479
}
2480

2481
impl AsRef<bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor>> for Wallet {
2482
    fn as_ref(&self) -> &bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor> {
×
2483
        self.indexed_graph.graph()
×
2484
    }
×
2485
}
2486

2487
/// Deterministically generate a unique name given the descriptors defining the wallet
2488
///
2489
/// Compatible with [`wallet_name_from_descriptor`]
2490
pub fn wallet_name_from_descriptor<T>(
×
2491
    descriptor: T,
×
2492
    change_descriptor: Option<T>,
×
2493
    network: Network,
×
2494
    secp: &SecpCtx,
×
2495
) -> Result<String, DescriptorError>
×
2496
where
×
2497
    T: IntoWalletDescriptor,
×
2498
{
×
2499
    //TODO check descriptors contains only public keys
2500
    let descriptor = descriptor
×
2501
        .into_wallet_descriptor(secp, network)?
×
2502
        .0
2503
        .to_string();
×
2504
    let mut wallet_name = calc_checksum(&descriptor[..descriptor.find('#').unwrap()])?;
×
2505
    if let Some(change_descriptor) = change_descriptor {
×
2506
        let change_descriptor = change_descriptor
×
2507
            .into_wallet_descriptor(secp, network)?
×
2508
            .0
2509
            .to_string();
×
2510
        wallet_name.push_str(
×
2511
            calc_checksum(&change_descriptor[..change_descriptor.find('#').unwrap()])?.as_str(),
×
2512
        );
2513
    }
×
2514

2515
    Ok(wallet_name)
×
2516
}
×
2517

2518
fn new_local_utxo(
1,400✔
2519
    keychain: KeychainKind,
1,400✔
2520
    derivation_index: u32,
1,400✔
2521
    full_txo: FullTxOut<ConfirmationTimeHeightAnchor>,
1,400✔
2522
) -> LocalOutput {
1,400✔
2523
    LocalOutput {
1,400✔
2524
        outpoint: full_txo.outpoint,
1,400✔
2525
        txout: full_txo.txout,
1,400✔
2526
        is_spent: full_txo.spent_by.is_some(),
1,400✔
2527
        confirmation_time: full_txo.chain_position.into(),
1,400✔
2528
        keychain,
1,400✔
2529
        derivation_index,
1,400✔
2530
    }
1,400✔
2531
}
1,400✔
2532

2533
fn create_signers<E: IntoWalletDescriptor>(
165✔
2534
    index: &mut KeychainTxOutIndex<KeychainKind>,
165✔
2535
    secp: &Secp256k1<All>,
165✔
2536
    descriptor: E,
165✔
2537
    change_descriptor: E,
165✔
2538
    network: Network,
165✔
2539
) -> Result<(Arc<SignersContainer>, Arc<SignersContainer>), DescriptorError> {
165✔
2540
    let descriptor = into_wallet_descriptor_checked(descriptor, secp, network)?;
165✔
2541
    let change_descriptor = into_wallet_descriptor_checked(change_descriptor, secp, network)?;
165✔
2542
    if descriptor.0 == change_descriptor.0 {
165✔
2543
        return Err(DescriptorError::ExternalAndInternalAreTheSame);
2✔
2544
    }
163✔
2545

163✔
2546
    let (descriptor, keymap) = descriptor;
163✔
2547
    let signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
163✔
2548
    let _ = index.insert_descriptor(KeychainKind::External, descriptor);
163✔
2549

163✔
2550
    let (descriptor, keymap) = change_descriptor;
163✔
2551
    let change_signers = Arc::new(SignersContainer::build(keymap, &descriptor, secp));
163✔
2552
    let _ = index.insert_descriptor(KeychainKind::Internal, descriptor);
163✔
2553

163✔
2554
    Ok((signers, change_signers))
163✔
2555
}
165✔
2556

2557
/// Transforms a [`FeeRate`] to `f64` with unit as sat/vb.
2558
#[macro_export]
2559
#[doc(hidden)]
2560
macro_rules! floating_rate {
2561
    ($rate:expr) => {{
2562
        use $crate::bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
2563
        // sat_kwu / 250.0 -> sat_vb
2564
        $rate.to_sat_per_kwu() as f64 / ((1000 / WITNESS_SCALE_FACTOR) as f64)
2565
    }};
2566
}
2567

2568
#[macro_export]
2569
#[doc(hidden)]
2570
/// Macro for getting a wallet for use in a doctest
2571
macro_rules! doctest_wallet {
2572
    () => {{
2573
        use $crate::bitcoin::{BlockHash, Transaction, absolute, TxOut, Network, hashes::Hash};
2574
        use $crate::chain::{ConfirmationTime, BlockId};
2575
        use $crate::{KeychainKind, wallet::Wallet};
2576
        let descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/0/*)";
2577
        let change_descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/1/*)";
2578

2579
        let mut wallet = Wallet::new_no_persist(
2580
            descriptor,
2581
            change_descriptor,
2582
            Network::Regtest,
2583
        )
2584
        .unwrap();
2585
        let address = wallet.peek_address(KeychainKind::External, 0).address;
2586
        let tx = Transaction {
2587
            version: transaction::Version::ONE,
2588
            lock_time: absolute::LockTime::ZERO,
2589
            input: vec![],
2590
            output: vec![TxOut {
2591
                value: Amount::from_sat(500_000),
2592
                script_pubkey: address.script_pubkey(),
2593
            }],
2594
        };
2595
        let _ = wallet.insert_checkpoint(BlockId { height: 1_000, hash: BlockHash::all_zeros() });
2596
        let _ = wallet.insert_tx(tx.clone(), ConfirmationTime::Confirmed {
2597
            height: 500,
2598
            time: 50_000
2599
        });
2600

2601
        wallet
2602
    }}
2603
}
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