-
Notifications
You must be signed in to change notification settings - Fork 306
/
mod.rs
2636 lines (2418 loc) · 103 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Wallet
//!
//! This module defines the [`Wallet`].
use crate::{
collections::{BTreeMap, HashMap},
descriptor::check_wallet_descriptor,
};
use alloc::{
boxed::Box,
string::{String, ToString},
sync::Arc,
vec::Vec,
};
pub use bdk_chain::Balance;
use bdk_chain::{
indexed_tx_graph,
indexer::keychain_txout::KeychainTxOutIndex,
local_chain::{
self, ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain,
},
spk_client::{
FullScanRequest, FullScanRequestBuilder, FullScanResult, SyncRequest, SyncRequestBuilder,
SyncResult,
},
tx_graph::{CanonicalTx, TxGraph, TxNode, TxUpdate},
BlockId, ChainPosition, ConfirmationBlockTime, ConfirmationTime, DescriptorExt, FullTxOut,
Indexed, IndexedTxGraph, Merge,
};
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
use bitcoin::{
absolute, psbt, Address, Block, FeeRate, Network, OutPoint, ScriptBuf, Sequence, Transaction,
TxOut, Txid, Witness,
};
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
use bitcoin::{constants::genesis_block, Amount};
use bitcoin::{secp256k1::Secp256k1, Weight};
use core::fmt;
use core::mem;
use core::ops::Deref;
use rand_core::RngCore;
use descriptor::error::Error as DescriptorError;
use miniscript::{
descriptor::KeyMap,
psbt::{PsbtExt, PsbtInputExt, PsbtInputSatisfier},
};
use bdk_chain::tx_graph::CalculateFeeError;
mod changeset;
pub mod coin_selection;
pub mod export;
mod params;
pub mod signer;
pub mod tx_builder;
pub use changeset::*;
pub use params::*;
mod persisted;
pub use persisted::*;
pub(crate) mod utils;
pub mod error;
pub use utils::IsDust;
use coin_selection::DefaultCoinSelectionAlgorithm;
use signer::{SignOptions, SignerOrdering, SignersContainer, TransactionSigner};
use tx_builder::{FeePolicy, TxBuilder, TxParams};
use utils::{check_nsequence_rbf, After, Older, SecpCtx};
use crate::descriptor::policy::BuildSatisfaction;
use crate::descriptor::{
self, DerivedDescriptor, DescriptorMeta, ExtendedDescriptor, ExtractPolicy,
IntoWalletDescriptor, Policy, XKeyUtils,
};
use crate::psbt::PsbtUtils;
use crate::signer::SignerError;
use crate::types::*;
use crate::wallet::coin_selection::Excess::{Change, NoChange};
use crate::wallet::error::{BuildFeeBumpError, CreateTxError, MiniscriptPsbtError};
use self::coin_selection::Error;
const COINBASE_MATURITY: u32 = 100;
/// A Bitcoin wallet
///
/// The `Wallet` acts as a way of coherently interfacing with output descriptors and related transactions.
/// Its main components are:
///
/// 1. output *descriptors* from which it can derive addresses.
/// 2. [`signer`]s that can contribute signatures to addresses instantiated from the descriptors.
///
/// The user is responsible for loading and writing wallet changes which are represented as
/// [`ChangeSet`]s (see [`take_staged`]). Also see individual functions and example for instructions
/// on when [`Wallet`] state needs to be persisted.
///
/// The `Wallet` descriptor (external) and change descriptor (internal) must not derive the same
/// script pubkeys. See [`KeychainTxOutIndex::insert_descriptor()`] for more details.
///
/// [`signer`]: crate::signer
/// [`take_staged`]: Wallet::take_staged
#[derive(Debug)]
pub struct Wallet {
signers: Arc<SignersContainer>,
change_signers: Arc<SignersContainer>,
chain: LocalChain,
indexed_graph: IndexedTxGraph<ConfirmationBlockTime, KeychainTxOutIndex<KeychainKind>>,
stage: ChangeSet,
network: Network,
secp: SecpCtx,
}
/// An update to [`Wallet`].
///
/// It updates [`KeychainTxOutIndex`], [`bdk_chain::TxGraph`] and [`local_chain::LocalChain`] atomically.
#[derive(Debug, Clone, Default)]
pub struct Update {
/// Contains the last active derivation indices per keychain (`K`), which is used to update the
/// [`KeychainTxOutIndex`].
pub last_active_indices: BTreeMap<KeychainKind, u32>,
/// Update for the wallet's internal [`TxGraph`].
pub tx_update: TxUpdate<ConfirmationBlockTime>,
/// Update for the wallet's internal [`LocalChain`].
///
/// [`LocalChain`]: local_chain::LocalChain
pub chain: Option<CheckPoint>,
}
impl From<FullScanResult<KeychainKind>> for Update {
fn from(value: FullScanResult<KeychainKind>) -> Self {
Self {
last_active_indices: value.last_active_indices,
tx_update: value.tx_update,
chain: value.chain_update,
}
}
}
impl From<SyncResult> for Update {
fn from(value: SyncResult) -> Self {
Self {
last_active_indices: BTreeMap::new(),
tx_update: value.tx_update,
chain: value.chain_update,
}
}
}
/// A derived address and the index it was found at.
/// For convenience this automatically derefs to `Address`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressInfo {
/// Child index of this address
pub index: u32,
/// Address
pub address: Address,
/// Type of keychain
pub keychain: KeychainKind,
}
impl Deref for AddressInfo {
type Target = Address;
fn deref(&self) -> &Self::Target {
&self.address
}
}
impl fmt::Display for AddressInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.address)
}
}
/// The error type when loading a [`Wallet`] from a [`ChangeSet`].
#[derive(Debug, PartialEq)]
pub enum LoadError {
/// There was a problem with the passed-in descriptor(s).
Descriptor(crate::descriptor::DescriptorError),
/// Data loaded from persistence is missing network type.
MissingNetwork,
/// Data loaded from persistence is missing genesis hash.
MissingGenesis,
/// Data loaded from persistence is missing descriptor.
MissingDescriptor(KeychainKind),
/// Data loaded is unexpected.
Mismatch(LoadMismatch),
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadError::Descriptor(e) => e.fmt(f),
LoadError::MissingNetwork => write!(f, "loaded data is missing network type"),
LoadError::MissingGenesis => write!(f, "loaded data is missing genesis hash"),
LoadError::MissingDescriptor(k) => {
write!(f, "loaded data is missing descriptor for keychain {k:?}")
}
LoadError::Mismatch(mismatch) => write!(f, "data mismatch: {mismatch:?}"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for LoadError {}
/// Represents a mismatch with what is loaded and what is expected from [`LoadParams`].
#[derive(Debug, PartialEq)]
pub enum LoadMismatch {
/// Network does not match.
Network {
/// The network that is loaded.
loaded: Network,
/// The expected network.
expected: Network,
},
/// Genesis hash does not match.
Genesis {
/// The genesis hash that is loaded.
loaded: BlockHash,
/// The expected genesis hash.
expected: BlockHash,
},
/// Descriptor's [`DescriptorId`](bdk_chain::DescriptorId) does not match.
Descriptor {
/// Keychain identifying the descriptor.
keychain: KeychainKind,
/// The loaded descriptor.
loaded: Option<ExtendedDescriptor>,
/// The expected descriptor.
expected: Option<ExtendedDescriptor>,
},
}
impl From<LoadMismatch> for LoadError {
fn from(mismatch: LoadMismatch) -> Self {
Self::Mismatch(mismatch)
}
}
impl<E> From<LoadMismatch> for LoadWithPersistError<E> {
fn from(mismatch: LoadMismatch) -> Self {
Self::InvalidChangeSet(LoadError::Mismatch(mismatch))
}
}
/// An error that may occur when applying a block to [`Wallet`].
#[derive(Debug)]
pub enum ApplyBlockError {
/// Occurs when the update chain cannot connect with original chain.
CannotConnect(CannotConnectError),
/// Occurs when the `connected_to` hash does not match the hash derived from `block`.
UnexpectedConnectedToHash {
/// Block hash of `connected_to`.
connected_to_hash: BlockHash,
/// Expected block hash of `connected_to`, as derived from `block`.
expected_hash: BlockHash,
},
}
impl fmt::Display for ApplyBlockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ApplyBlockError::CannotConnect(err) => err.fmt(f),
ApplyBlockError::UnexpectedConnectedToHash {
expected_hash: block_hash,
connected_to_hash: checkpoint_hash,
} => write!(
f,
"`connected_to` hash {} differs from the expected hash {} (which is derived from `block`)",
checkpoint_hash, block_hash
),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ApplyBlockError {}
impl Wallet {
/// Build a new single descriptor [`Wallet`].
///
/// If you have previously created a wallet, use [`load`](Self::load) instead.
///
/// # Note
///
/// Only use this method when creating a wallet designed to be used with a single
/// descriptor and keychain. Otherwise the recommended way to construct a new wallet is
/// by using [`Wallet::create`]. It's worth noting that not all features are available
/// with single descriptor wallets, for example setting a [`change_policy`] on [`TxBuilder`]
/// and related methods such as [`do_not_spend_change`]. This is because all payments are
/// received on the external keychain (including change), and without a change keychain
/// BDK lacks enough information to distinguish between change and outside payments.
///
/// Additionally because this wallet has no internal (change) keychain, all methods that
/// require a [`KeychainKind`] as input, e.g. [`reveal_next_address`] should only be called
/// using the [`External`] variant. In most cases passing [`Internal`] is treated as the
/// equivalent of [`External`] but can lead to confusing results.
///
/// # Example
///
/// ```rust
/// # use bdk_wallet::Wallet;
/// # use bitcoin::Network;
/// # const EXTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
/// # let temp_dir = tempfile::tempdir().expect("must create tempdir");
/// # let file_path = temp_dir.path().join("store.db");
/// // Create a wallet that is persisted to SQLite database.
/// use bdk_wallet::rusqlite::Connection;
/// let mut conn = Connection::open(file_path)?;
/// let wallet = Wallet::create_single(EXTERNAL_DESC)
/// .network(Network::Testnet)
/// .create_wallet(&mut conn)?;
/// # Ok::<_, anyhow::Error>(())
/// ```
/// [`change_policy`]: TxBuilder::change_policy
/// [`do_not_spend_change`]: TxBuilder::do_not_spend_change
/// [`External`]: KeychainKind::External
/// [`Internal`]: KeychainKind::Internal
/// [`reveal_next_address`]: Self::reveal_next_address
pub fn create_single<D>(descriptor: D) -> CreateParams
where
D: IntoWalletDescriptor + Send + Clone + 'static,
{
CreateParams::new_single(descriptor)
}
/// Build a new [`Wallet`].
///
/// If you have previously created a wallet, use [`load`](Self::load) instead.
///
/// # Synopsis
///
/// ```rust
/// # use bdk_wallet::Wallet;
/// # use bitcoin::Network;
/// # fn main() -> anyhow::Result<()> {
/// # const EXTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
/// # const INTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
/// // Create a non-persisted wallet.
/// let wallet = Wallet::create(EXTERNAL_DESC, INTERNAL_DESC)
/// .network(Network::Testnet)
/// .create_wallet_no_persist()?;
///
/// // Create a wallet that is persisted to SQLite database.
/// # let temp_dir = tempfile::tempdir().expect("must create tempdir");
/// # let file_path = temp_dir.path().join("store.db");
/// use bdk_wallet::rusqlite::Connection;
/// let mut conn = Connection::open(file_path)?;
/// let wallet = Wallet::create(EXTERNAL_DESC, INTERNAL_DESC)
/// .network(Network::Testnet)
/// .create_wallet(&mut conn)?;
/// # Ok(())
/// # }
/// ```
pub fn create<D>(descriptor: D, change_descriptor: D) -> CreateParams
where
D: IntoWalletDescriptor + Send + Clone + 'static,
{
CreateParams::new(descriptor, change_descriptor)
}
/// Create a new [`Wallet`] with given `params`.
///
/// Refer to [`Wallet::create`] for more.
pub fn create_with_params(params: CreateParams) -> Result<Self, DescriptorError> {
let secp = SecpCtx::new();
let network = params.network;
let genesis_hash = params
.genesis_hash
.unwrap_or(genesis_block(network).block_hash());
let (chain, chain_changeset) = LocalChain::from_genesis_hash(genesis_hash);
let (descriptor, mut descriptor_keymap) = (params.descriptor)(&secp, network)?;
descriptor_keymap.extend(params.descriptor_keymap);
let signers = Arc::new(SignersContainer::build(
descriptor_keymap,
&descriptor,
&secp,
));
let (change_descriptor, change_signers) = match params.change_descriptor {
Some(make_desc) => {
let (change_descriptor, mut internal_keymap) = make_desc(&secp, network)?;
internal_keymap.extend(params.change_descriptor_keymap);
let change_signers = Arc::new(SignersContainer::build(
internal_keymap,
&change_descriptor,
&secp,
));
(Some(change_descriptor), change_signers)
}
None => (None, Arc::new(SignersContainer::new())),
};
let index = create_indexer(descriptor, change_descriptor, params.lookahead)?;
let descriptor = index.get_descriptor(KeychainKind::External).cloned();
let change_descriptor = index.get_descriptor(KeychainKind::Internal).cloned();
let indexed_graph = IndexedTxGraph::new(index);
let indexed_graph_changeset = indexed_graph.initial_changeset();
let stage = ChangeSet {
descriptor,
change_descriptor,
local_chain: chain_changeset,
tx_graph: indexed_graph_changeset.tx_graph,
indexer: indexed_graph_changeset.indexer,
network: Some(network),
};
Ok(Wallet {
signers,
change_signers,
network,
chain,
indexed_graph,
stage,
secp,
})
}
/// Build [`Wallet`] by loading from persistence or [`ChangeSet`].
///
/// Note that the descriptor secret keys are not persisted to the db. You can add
/// signers after-the-fact with [`Wallet::add_signer`] or [`Wallet::set_keymap`]. You
/// can also add keys when building the wallet by using [`LoadParams::keymap`]. Finally
/// you can check the wallet's descriptors are what you expect with [`LoadParams::descriptor`]
/// which will try to populate signers if [`LoadParams::extract_keys`] is enabled.
///
/// # Synopsis
///
/// ```rust,no_run
/// # use bdk_wallet::{Wallet, ChangeSet, KeychainKind};
/// # use bitcoin::{BlockHash, Network, hashes::Hash};
/// # fn main() -> anyhow::Result<()> {
/// # const EXTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)";
/// # const INTERNAL_DESC: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/1/*)";
/// # let changeset = ChangeSet::default();
/// // Load a wallet from changeset (no persistence).
/// let wallet = Wallet::load()
/// .load_wallet_no_persist(changeset)?
/// .expect("must have data to load wallet");
///
/// // Load a wallet that is persisted to SQLite database.
/// # let temp_dir = tempfile::tempdir().expect("must create tempdir");
/// # let file_path = temp_dir.path().join("store.db");
/// # let external_keymap = Default::default();
/// # let internal_keymap = Default::default();
/// # let genesis_hash = BlockHash::all_zeros();
/// let mut conn = bdk_wallet::rusqlite::Connection::open(file_path)?;
/// let mut wallet = Wallet::load()
/// // check loaded descriptors matches these values and extract private keys
/// .descriptor(KeychainKind::External, Some(EXTERNAL_DESC))
/// .descriptor(KeychainKind::Internal, Some(INTERNAL_DESC))
/// .extract_keys()
/// // you can also manually add private keys
/// .keymap(KeychainKind::External, external_keymap)
/// .keymap(KeychainKind::Internal, internal_keymap)
/// // ensure loaded wallet's genesis hash matches this value
/// .check_genesis_hash(genesis_hash)
/// // set a lookahead for our indexer
/// .lookahead(101)
/// .load_wallet(&mut conn)?
/// .expect("must have data to load wallet");
/// # Ok(())
/// # }
/// ```
pub fn load() -> LoadParams {
LoadParams::new()
}
/// Load [`Wallet`] from the given previously persisted [`ChangeSet`] and `params`.
///
/// Refer to [`Wallet::load`] for more.
pub fn load_with_params(
changeset: ChangeSet,
params: LoadParams,
) -> Result<Option<Self>, LoadError> {
if changeset.is_empty() {
return Ok(None);
}
let secp = Secp256k1::new();
let network = changeset.network.ok_or(LoadError::MissingNetwork)?;
let chain = LocalChain::from_changeset(changeset.local_chain)
.map_err(|_| LoadError::MissingGenesis)?;
if let Some(exp_network) = params.check_network {
if network != exp_network {
return Err(LoadError::Mismatch(LoadMismatch::Network {
loaded: network,
expected: exp_network,
}));
}
}
if let Some(exp_genesis_hash) = params.check_genesis_hash {
if chain.genesis_hash() != exp_genesis_hash {
return Err(LoadError::Mismatch(LoadMismatch::Genesis {
loaded: chain.genesis_hash(),
expected: exp_genesis_hash,
}));
}
}
let descriptor = changeset
.descriptor
.ok_or(LoadError::MissingDescriptor(KeychainKind::External))?;
check_wallet_descriptor(&descriptor).map_err(LoadError::Descriptor)?;
let mut external_keymap = params.descriptor_keymap;
if let Some(expected) = params.check_descriptor {
if let Some(make_desc) = expected {
let (exp_desc, keymap) =
make_desc(&secp, network).map_err(LoadError::Descriptor)?;
if descriptor.descriptor_id() != exp_desc.descriptor_id() {
return Err(LoadError::Mismatch(LoadMismatch::Descriptor {
keychain: KeychainKind::External,
loaded: Some(descriptor),
expected: Some(exp_desc),
}));
}
if params.extract_keys {
external_keymap.extend(keymap);
}
} else {
return Err(LoadError::Mismatch(LoadMismatch::Descriptor {
keychain: KeychainKind::External,
loaded: Some(descriptor),
expected: None,
}));
}
}
let signers = Arc::new(SignersContainer::build(external_keymap, &descriptor, &secp));
let (mut change_descriptor, mut change_signers) = (None, Arc::new(SignersContainer::new()));
match (changeset.change_descriptor, params.check_change_descriptor) {
// empty signer
(None, None) => {}
(None, Some(expect)) => {
// expected desc but none loaded
if let Some(make_desc) = expect {
let (exp_desc, _) = make_desc(&secp, network).map_err(LoadError::Descriptor)?;
return Err(LoadError::Mismatch(LoadMismatch::Descriptor {
keychain: KeychainKind::Internal,
loaded: None,
expected: Some(exp_desc),
}));
}
}
// nothing expected
(Some(desc), None) => {
check_wallet_descriptor(&desc).map_err(LoadError::Descriptor)?;
change_descriptor = Some(desc);
}
(Some(desc), Some(expect)) => match expect {
// expected none for existing
None => {
return Err(LoadError::Mismatch(LoadMismatch::Descriptor {
keychain: KeychainKind::Internal,
loaded: Some(desc),
expected: None,
}))
}
// parameters must match
Some(make_desc) => {
let (exp_desc, keymap) =
make_desc(&secp, network).map_err(LoadError::Descriptor)?;
if desc.descriptor_id() != exp_desc.descriptor_id() {
return Err(LoadError::Mismatch(LoadMismatch::Descriptor {
keychain: KeychainKind::Internal,
loaded: Some(desc),
expected: Some(exp_desc),
}));
}
let mut internal_keymap = params.change_descriptor_keymap;
if params.extract_keys {
internal_keymap.extend(keymap);
}
change_signers =
Arc::new(SignersContainer::build(internal_keymap, &desc, &secp));
change_descriptor = Some(desc);
}
},
}
let index = create_indexer(descriptor, change_descriptor, params.lookahead)
.map_err(LoadError::Descriptor)?;
let mut indexed_graph = IndexedTxGraph::new(index);
indexed_graph.apply_changeset(changeset.indexer.into());
indexed_graph.apply_changeset(changeset.tx_graph.into());
let stage = ChangeSet::default();
Ok(Some(Wallet {
signers,
change_signers,
chain,
indexed_graph,
stage,
network,
secp,
}))
}
/// Get the Bitcoin network the wallet is using.
pub fn network(&self) -> Network {
self.network
}
/// Iterator over all keychains in this wallet
pub fn keychains(&self) -> impl Iterator<Item = (KeychainKind, &ExtendedDescriptor)> {
self.indexed_graph.index.keychains()
}
/// Peek an address of the given `keychain` at `index` without revealing it.
///
/// For non-wildcard descriptors this returns the same address at every provided index.
///
/// # Panics
///
/// This panics when the caller requests for an address of derivation index greater than the
/// [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) max index.
pub fn peek_address(&self, keychain: KeychainKind, mut index: u32) -> AddressInfo {
let keychain = self.map_keychain(keychain);
let mut spk_iter = self
.indexed_graph
.index
.unbounded_spk_iter(keychain)
.expect("keychain must exist");
if !spk_iter.descriptor().has_wildcard() {
index = 0;
}
let (index, spk) = spk_iter
.nth(index as usize)
.expect("derivation index is out of bounds");
AddressInfo {
index,
address: Address::from_script(&spk, self.network).expect("must have address form"),
keychain,
}
}
/// Attempt to reveal the next address of the given `keychain`.
///
/// This will increment the keychain's derivation index. If the keychain's descriptor doesn't
/// contain a wildcard or every address is already revealed up to the maximum derivation
/// index defined in [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
/// then the last revealed address will be returned.
///
/// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
/// calls to this method before closing the wallet. For example:
///
/// ```rust,no_run
/// # use bdk_wallet::{LoadParams, ChangeSet, KeychainKind};
/// use bdk_chain::rusqlite::Connection;
/// let mut conn = Connection::open_in_memory().expect("must open connection");
/// let mut wallet = LoadParams::new()
/// .load_wallet(&mut conn)
/// .expect("database is okay")
/// .expect("database has data");
/// let next_address = wallet.reveal_next_address(KeychainKind::External);
/// wallet.persist(&mut conn).expect("write is okay");
///
/// // Now it's safe to show the user their next address!
/// println!("Next address: {}", next_address.address);
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn reveal_next_address(&mut self, keychain: KeychainKind) -> AddressInfo {
let keychain = self.map_keychain(keychain);
let index = &mut self.indexed_graph.index;
let stage = &mut self.stage;
let ((index, spk), index_changeset) = index
.reveal_next_spk(keychain)
.expect("keychain must exist");
stage.merge(index_changeset.into());
AddressInfo {
index,
address: Address::from_script(spk.as_script(), self.network)
.expect("must have address form"),
keychain,
}
}
/// Reveal addresses up to and including the target `index` and return an iterator
/// of newly revealed addresses.
///
/// If the target `index` is unreachable, we make a best effort to reveal up to the last
/// possible index. If all addresses up to the given `index` are already revealed, then
/// no new addresses are returned.
///
/// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
/// calls to this method before closing the wallet. See [`Wallet::reveal_next_address`].
pub fn reveal_addresses_to(
&mut self,
keychain: KeychainKind,
index: u32,
) -> impl Iterator<Item = AddressInfo> + '_ {
let keychain = self.map_keychain(keychain);
let (spks, index_changeset) = self
.indexed_graph
.index
.reveal_to_target(keychain, index)
.expect("keychain must exist");
self.stage.merge(index_changeset.into());
spks.into_iter().map(move |(index, spk)| AddressInfo {
index,
address: Address::from_script(&spk, self.network).expect("must have address form"),
keychain,
})
}
/// Get the next unused address for the given `keychain`, i.e. the address with the lowest
/// derivation index that hasn't been used.
///
/// This will attempt to derive and reveal a new address if no newly revealed addresses
/// are available. See also [`reveal_next_address`](Self::reveal_next_address).
///
/// **WARNING**: To avoid address reuse you must persist the changes resulting from one or more
/// calls to this method before closing the wallet. See [`Wallet::reveal_next_address`].
pub fn next_unused_address(&mut self, keychain: KeychainKind) -> AddressInfo {
let keychain = self.map_keychain(keychain);
let index = &mut self.indexed_graph.index;
let ((index, spk), index_changeset) = index
.next_unused_spk(keychain)
.expect("keychain must exist");
self.stage
.merge(indexed_tx_graph::ChangeSet::from(index_changeset).into());
AddressInfo {
index,
address: Address::from_script(spk.as_script(), self.network)
.expect("must have address form"),
keychain,
}
}
/// Marks an address used of the given `keychain` at `index`.
///
/// Returns whether the given index was present and then removed from the unused set.
pub fn mark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
self.indexed_graph.index.mark_used(keychain, index)
}
/// Undoes the effect of [`mark_used`] and returns whether the `index` was inserted
/// back into the unused set.
///
/// Since this is only a superficial marker, it will have no effect if the address at the given
/// `index` was actually used, i.e. the wallet has previously indexed a tx output for the
/// derived spk.
///
/// [`mark_used`]: Self::mark_used
pub fn unmark_used(&mut self, keychain: KeychainKind, index: u32) -> bool {
self.indexed_graph.index.unmark_used(keychain, index)
}
/// List addresses that are revealed but unused.
///
/// Note if the returned iterator is empty you can reveal more addresses
/// by using [`reveal_next_address`](Self::reveal_next_address) or
/// [`reveal_addresses_to`](Self::reveal_addresses_to).
pub fn list_unused_addresses(
&self,
keychain: KeychainKind,
) -> impl DoubleEndedIterator<Item = AddressInfo> + '_ {
self.indexed_graph
.index
.unused_keychain_spks(self.map_keychain(keychain))
.map(move |(index, spk)| AddressInfo {
index,
address: Address::from_script(spk.as_script(), self.network)
.expect("must have address form"),
keychain,
})
}
/// Return whether or not a `script` is part of this wallet (either internal or external)
pub fn is_mine(&self, script: ScriptBuf) -> bool {
self.indexed_graph.index.index_of_spk(script).is_some()
}
/// Finds how the wallet derived the script pubkey `spk`.
///
/// Will only return `Some(_)` if the wallet has given out the spk.
pub fn derivation_of_spk(&self, spk: ScriptBuf) -> Option<(KeychainKind, u32)> {
self.indexed_graph.index.index_of_spk(spk).cloned()
}
/// Return the list of unspent outputs of this wallet
pub fn list_unspent(&self) -> impl Iterator<Item = LocalOutput> + '_ {
self.indexed_graph
.graph()
.filter_chain_unspents(
&self.chain,
self.chain.tip().block_id(),
self.indexed_graph.index.outpoints().iter().cloned(),
)
.map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
}
/// List all relevant outputs (includes both spent and unspent, confirmed and unconfirmed).
///
/// To list only unspent outputs (UTXOs), use [`Wallet::list_unspent`] instead.
pub fn list_output(&self) -> impl Iterator<Item = LocalOutput> + '_ {
self.indexed_graph
.graph()
.filter_chain_txouts(
&self.chain,
self.chain.tip().block_id(),
self.indexed_graph.index.outpoints().iter().cloned(),
)
.map(|((k, i), full_txo)| new_local_utxo(k, i, full_txo))
}
/// Get all the checkpoints the wallet is currently storing indexed by height.
pub fn checkpoints(&self) -> CheckPointIter {
self.chain.iter_checkpoints()
}
/// Returns the latest checkpoint.
pub fn latest_checkpoint(&self) -> CheckPoint {
self.chain.tip()
}
/// Get unbounded script pubkey iterators for both `Internal` and `External` keychains.
///
/// This is intended to be used when doing a full scan of your addresses (e.g. after restoring
/// from seed words). You pass the `BTreeMap` of iterators to a blockchain data source (e.g.
/// electrum server) which will go through each address until it reaches a *stop gap*.
///
/// Note carefully that iterators go over **all** script pubkeys on the keychains (not what
/// script pubkeys the wallet is storing internally).
pub fn all_unbounded_spk_iters(
&self,
) -> BTreeMap<KeychainKind, impl Iterator<Item = Indexed<ScriptBuf>> + Clone> {
self.indexed_graph.index.all_unbounded_spk_iters()
}
/// Get an unbounded script pubkey iterator for the given `keychain`.
///
/// See [`all_unbounded_spk_iters`] for more documentation
///
/// [`all_unbounded_spk_iters`]: Self::all_unbounded_spk_iters
pub fn unbounded_spk_iter(
&self,
keychain: KeychainKind,
) -> impl Iterator<Item = Indexed<ScriptBuf>> + Clone {
self.indexed_graph
.index
.unbounded_spk_iter(self.map_keychain(keychain))
.expect("keychain must exist")
}
/// Returns the utxo owned by this wallet corresponding to `outpoint` if it exists in the
/// wallet's database.
pub fn get_utxo(&self, op: OutPoint) -> Option<LocalOutput> {
let ((keychain, index), _) = self.indexed_graph.index.txout(op)?;
self.indexed_graph
.graph()
.filter_chain_unspents(
&self.chain,
self.chain.tip().block_id(),
core::iter::once(((), op)),
)
.map(|(_, full_txo)| new_local_utxo(keychain, index, full_txo))
.next()
}
/// Inserts a [`TxOut`] at [`OutPoint`] into the wallet's transaction graph.
///
/// This is used for providing a previous output's value so that we can use [`calculate_fee`]
/// or [`calculate_fee_rate`] on a given transaction. Outputs inserted with this method will
/// not be returned in [`list_unspent`] or [`list_output`].
///
/// **WARNINGS:** This should only be used to add `TxOut`s that the wallet does not own. Only
/// insert `TxOut`s that you trust the values for!
///
/// You must persist the changes resulting from one or more calls to this method if you need
/// the inserted `TxOut` data to be reloaded after closing the wallet.
/// See [`Wallet::reveal_next_address`].
///
/// [`calculate_fee`]: Self::calculate_fee
/// [`calculate_fee_rate`]: Self::calculate_fee_rate
/// [`list_unspent`]: Self::list_unspent
/// [`list_output`]: Self::list_output
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) {
let additions = self.indexed_graph.insert_txout(outpoint, txout);
self.stage.merge(additions.into());
}
/// Calculates the fee of a given transaction. Returns [`Amount::ZERO`] if `tx` is a coinbase transaction.
///
/// To calculate the fee for a [`Transaction`] with inputs not owned by this wallet you must
/// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
///
/// Note `tx` does not have to be in the graph for this to work.
///
/// # Examples
///
/// ```rust, no_run
/// # use bitcoin::Txid;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let txid:Txid = todo!();
/// let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
/// let fee = wallet.calculate_fee(&tx).expect("fee");
/// ```
///
/// ```rust, no_run
/// # use bitcoin::Psbt;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let mut psbt: Psbt = todo!();
/// let tx = &psbt.clone().extract_tx().expect("tx");
/// let fee = wallet.calculate_fee(tx).expect("fee");
/// ```
/// [`insert_txout`]: Self::insert_txout
pub fn calculate_fee(&self, tx: &Transaction) -> Result<Amount, CalculateFeeError> {
self.indexed_graph.graph().calculate_fee(tx)
}
/// Calculate the [`FeeRate`] for a given transaction.
///
/// To calculate the fee rate for a [`Transaction`] with inputs not owned by this wallet you must
/// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
///
/// Note `tx` does not have to be in the graph for this to work.
///
/// # Examples
///
/// ```rust, no_run
/// # use bitcoin::Txid;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let txid:Txid = todo!();
/// let tx = wallet.get_tx(txid).expect("transaction").tx_node.tx;
/// let fee_rate = wallet.calculate_fee_rate(&tx).expect("fee rate");
/// ```
///
/// ```rust, no_run
/// # use bitcoin::Psbt;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let mut psbt: Psbt = todo!();
/// let tx = &psbt.clone().extract_tx().expect("tx");
/// let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
/// ```
/// [`insert_txout`]: Self::insert_txout
pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<FeeRate, CalculateFeeError> {
self.calculate_fee(tx).map(|fee| fee / tx.weight())
}
/// Compute the `tx`'s sent and received [`Amount`]s.
///
/// This method returns a tuple `(sent, received)`. Sent is the sum of the txin amounts
/// that spend from previous txouts tracked by this wallet. Received is the summation
/// of this tx's outputs that send to script pubkeys tracked by this wallet.
///
/// # Examples
///
/// ```rust, no_run
/// # use bitcoin::Txid;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let txid:Txid = todo!();
/// let tx = wallet.get_tx(txid).expect("tx exists").tx_node.tx;
/// let (sent, received) = wallet.sent_and_received(&tx);
/// ```
///
/// ```rust, no_run
/// # use bitcoin::Psbt;
/// # use bdk_wallet::Wallet;
/// # let mut wallet: Wallet = todo!();
/// # let mut psbt: Psbt = todo!();
/// let tx = &psbt.clone().extract_tx().expect("tx");
/// let (sent, received) = wallet.sent_and_received(tx);
/// ```