Coverage Report

Created: 2026-07-23 20:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/wallet.h
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#ifndef BITCOIN_WALLET_WALLET_H
7
#define BITCOIN_WALLET_WALLET_H
8
9
#include <addresstype.h>
10
#include <consensus/amount.h>
11
#include <interfaces/chain.h>
12
#include <interfaces/handler.h>
13
#include <kernel/cs_main.h>
14
#include <node/types.h>
15
#include <outputtype.h>
16
#include <policy/feerate.h>
17
#include <primitives/transaction.h>
18
#include <primitives/transaction_identifier.h>
19
#include <script/interpreter.h>
20
#include <script/script.h>
21
#include <support/allocators/secure.h>
22
#include <sync.h>
23
#include <tinyformat.h>
24
#include <uint256.h>
25
#include <util/btcsignals.h>
26
#include <util/expected.h>
27
#include <util/fs.h>
28
#include <util/hasher.h>
29
#include <util/log.h>
30
#include <util/result.h>
31
#include <util/string.h>
32
#include <util/time.h>
33
#include <util/ui_change_type.h>
34
#include <wallet/crypter.h>
35
#include <wallet/db.h>
36
#include <wallet/scriptpubkeyman.h>
37
#include <wallet/transaction.h>
38
#include <wallet/types.h>
39
#include <wallet/walletutil.h>
40
41
#include <atomic>
42
#include <cassert>
43
#include <cstddef>
44
#include <cstdint>
45
#include <functional>
46
#include <limits>
47
#include <map>
48
#include <memory>
49
#include <optional>
50
#include <set>
51
#include <string>
52
#include <unordered_map>
53
#include <utility>
54
#include <vector>
55
56
class CKey;
57
class CKeyID;
58
class CPubKey;
59
class Coin;
60
class SigningProvider;
61
enum class MemPoolRemovalReason;
62
enum class SigningResult;
63
namespace common {
64
enum class PSBTError;
65
} // namespace common
66
namespace interfaces {
67
class Wallet;
68
}
69
namespace wallet {
70
class CWallet;
71
class WalletBatch;
72
enum class DBErrors : int;
73
} // namespace wallet
74
struct CBlockLocator;
75
struct CExtKey;
76
struct FlatSigningProvider;
77
struct KeyOriginInfo;
78
class PartiallySignedTransaction;
79
struct SignatureData;
80
81
using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
82
83
struct bilingual_str;
84
85
namespace wallet {
86
struct WalletContext;
87
88
//! Explicitly delete the wallet.
89
//! Blocks the current thread until the wallet is destructed.
90
void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet);
91
92
bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
93
bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
94
bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
95
std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
96
std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
97
std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
98
std::shared_ptr<CWallet> LoadWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
99
std::shared_ptr<CWallet> CreateWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
100
std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& backup_file, const std::string& wallet_name, std::optional<bool> load_on_start, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings, bool load_after_restore = true, bool allow_unnamed = false);
101
std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
102
void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
103
std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
104
105
//! -fallbackfee default
106
static const CAmount DEFAULT_FALLBACK_FEE = 0;
107
//! -discardfee default
108
static const CAmount DEFAULT_DISCARD_FEE = 10000;
109
//! -mintxfee default
110
static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
111
//! -consolidatefeerate default
112
static const CAmount DEFAULT_CONSOLIDATE_FEERATE{10000}; // 10 sat/vbyte
113
/**
114
 * maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled by default
115
 *
116
 * A value of -1 disables this feature completely.
117
 * A value of 0 (current default) means to attempt to do partial spend avoidance, and use its results if the fees remain *unchanged*
118
 * A value > 0 means to do partial spend avoidance if the fee difference against a regular coin selection instance is in the range [0..value].
119
 */
120
static const CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE = 0;
121
//! discourage APS fee higher than this amount
122
constexpr CAmount HIGH_APS_FEE{COIN / 10000};
123
//! minimum recommended increment for replacement txs
124
static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
125
//! Default for -spendzeroconfchange
126
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
127
//! Default for -walletrejectlongchains
128
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
129
//! -txconfirmtarget default
130
static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
131
//! -walletrbf default
132
static const bool DEFAULT_WALLET_RBF = true;
133
static const bool DEFAULT_WALLETBROADCAST = true;
134
static const bool DEFAULT_DISABLE_WALLET = false;
135
static const bool DEFAULT_WALLETCROSSCHAIN = false;
136
//! -maxtxfee default
137
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE{COIN / 10};
138
//! Discourage users to set fees higher than this amount (in satoshis) per kB
139
constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
140
//! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
141
constexpr CAmount HIGH_MAX_TX_FEE{100 * HIGH_TX_FEE_PER_KB};
142
//! Pre-calculated constants for input size estimation in *virtual size*
143
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
144
145
class CCoinControl;
146
147
//! Default for -addresstype
148
constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::BECH32};
149
150
static constexpr uint64_t KNOWN_WALLET_FLAGS =
151
        WALLET_FLAG_AVOID_REUSE
152
    |   WALLET_FLAG_BLANK_WALLET
153
    |   WALLET_FLAG_KEY_ORIGIN_METADATA
154
    |   WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
155
    |   WALLET_FLAG_DISABLE_PRIVATE_KEYS
156
    |   WALLET_FLAG_DESCRIPTORS
157
    |   WALLET_FLAG_EXTERNAL_SIGNER;
158
159
static constexpr uint64_t MUTABLE_WALLET_FLAGS =
160
        WALLET_FLAG_AVOID_REUSE;
161
162
static const std::map<WalletFlags, std::string> WALLET_FLAG_TO_STRING{
163
    {WALLET_FLAG_AVOID_REUSE, "avoid_reuse"},
164
    {WALLET_FLAG_BLANK_WALLET, "blank"},
165
    {WALLET_FLAG_KEY_ORIGIN_METADATA, "key_origin_metadata"},
166
    {WALLET_FLAG_LAST_HARDENED_XPUB_CACHED, "last_hardened_xpub_cached"},
167
    {WALLET_FLAG_DISABLE_PRIVATE_KEYS, "disable_private_keys"},
168
    {WALLET_FLAG_DESCRIPTORS, "descriptor_wallet"},
169
    {WALLET_FLAG_EXTERNAL_SIGNER, "external_signer"}
170
};
171
172
static const std::map<std::string, WalletFlags> STRING_TO_WALLET_FLAG{
173
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_AVOID_REUSE), WALLET_FLAG_AVOID_REUSE},
174
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_BLANK_WALLET), WALLET_FLAG_BLANK_WALLET},
175
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_KEY_ORIGIN_METADATA), WALLET_FLAG_KEY_ORIGIN_METADATA},
176
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED), WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
177
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_DISABLE_PRIVATE_KEYS), WALLET_FLAG_DISABLE_PRIVATE_KEYS},
178
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_DESCRIPTORS), WALLET_FLAG_DESCRIPTORS},
179
    {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_EXTERNAL_SIGNER), WALLET_FLAG_EXTERNAL_SIGNER}
180
};
181
182
/** A wrapper to reserve an address from a wallet
183
 *
184
 * ReserveDestination is used to reserve an address.
185
 * It is currently only used inside of CreateTransaction.
186
 *
187
 * Instantiating a ReserveDestination does not reserve an address. To do so,
188
 * GetReservedDestination() needs to be called on the object. Once an address has been
189
 * reserved, call KeepDestination() on the ReserveDestination object to make sure it is not
190
 * returned. Call ReturnDestination() to return the address so it can be reused (for
191
 * example, if the address was used in a new transaction
192
 * and that transaction was not completed and needed to be aborted).
193
 *
194
 * If an address is reserved and KeepDestination() is not called, then the address will be
195
 * returned when the ReserveDestination goes out of scope.
196
 */
197
class ReserveDestination
198
{
199
protected:
200
    //! The wallet to reserve from
201
    const CWallet* const pwallet;
202
    //! The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called
203
    ScriptPubKeyMan* m_spk_man{nullptr};
204
    OutputType const type;
205
    //! The index of the address's key in the keypool
206
    int64_t nIndex{-1};
207
    //! The destination
208
    CTxDestination address;
209
    //! Whether this is from the internal (change output) keypool
210
    bool fInternal{false};
211
212
public:
213
    //! Construct a ReserveDestination object. This does NOT reserve an address yet
214
    explicit ReserveDestination(CWallet* pwallet, OutputType type)
215
4.01k
      : pwallet(pwallet)
216
4.01k
      , type(type) { }
217
218
    ReserveDestination(const ReserveDestination&) = delete;
219
    ReserveDestination& operator=(const ReserveDestination&) = delete;
220
221
    //! Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool
222
    ~ReserveDestination()
223
4.01k
    {
224
4.01k
        ReturnDestination();
225
4.01k
    }
226
227
    //! Reserve an address
228
    util::Result<CTxDestination> GetReservedDestination(bool internal);
229
    //! Return reserved address
230
    void ReturnDestination();
231
    //! Keep the address. Do not return its key to the keypool when this object goes out of scope
232
    void KeepDestination();
233
};
234
235
/**
236
 * Address book data.
237
 */
238
struct CAddressBookData
239
{
240
    /**
241
     * Address label which is always nullopt for change addresses. For sending
242
     * and receiving addresses, it will be set to an arbitrary label string
243
     * provided by the user, or to "", which is the default label. The presence
244
     * or absence of a label is used to distinguish change addresses from
245
     * non-change addresses by wallet transaction listing and fee bumping code.
246
     */
247
    std::optional<std::string> label;
248
249
    /**
250
     * Address purpose which was originally recorded for payment protocol
251
     * support but now serves as a cached IsMine value. Wallet code should
252
     * not rely on this field being set.
253
     */
254
    std::optional<AddressPurpose> purpose;
255
256
    /**
257
     * Whether coins with this address have previously been spent. Set when the
258
     * the wallet avoid_reuse option is enabled and this is an IsMine address
259
     * that has already received funds and spent them. This is used during coin
260
     * selection to increase privacy by not creating different transactions
261
     * that spend from the same addresses.
262
     */
263
    bool previously_spent{false};
264
265
    /**
266
     * Map containing data about previously generated receive requests
267
     * requesting funds to be sent to this address. Only present for IsMine
268
     * addresses. Map keys are decimal numbers uniquely identifying each
269
     * request, and map values are serialized RecentRequestEntry objects
270
     * containing BIP21 URI information including message and amount.
271
     */
272
    std::map<std::string, std::string> receive_requests{};
273
274
    /** Accessor methods. */
275
12.0k
    bool IsChange() const { return !label.has_value(); }
276
11.0k
    std::string GetLabel() const { return label ? *label : std::string{}; }
277
30.2k
    void SetLabel(std::string name) { label = std::move(name); }
278
};
279
280
inline std::string PurposeToString(AddressPurpose p)
281
28.1k
{
282
28.1k
    switch(p) {
283
28.1k
    case AddressPurpose::RECEIVE: return "receive";
284
17
    case AddressPurpose::SEND: return "send";
285
0
    case AddressPurpose::REFUND: return "refund";
286
28.1k
    } // no default case, so the compiler can warn about missing cases
287
28.1k
    assert(false);
288
0
}
289
290
inline std::optional<AddressPurpose> PurposeFromString(std::string_view s)
291
2.24k
{
292
2.24k
    if (s == "receive") return AddressPurpose::RECEIVE;
293
42
    else if (s == "send") return AddressPurpose::SEND;
294
2
    else if (s == "refund") return AddressPurpose::REFUND;
295
2
    return {};
296
2.24k
}
297
298
struct CRecipient
299
{
300
    CTxDestination dest;
301
    CAmount nAmount;
302
    bool fSubtractFeeFromAmount;
303
};
304
305
class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
306
/**
307
 * A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.
308
 */
309
class CWallet final : public WalletStorage, public interfaces::Chain::Notifications
310
{
311
private:
312
    CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
313
314
    bool Unlock(const CKeyingMaterial& vMasterKeyIn);
315
316
    std::atomic<bool> fAbortRescan{false};
317
    std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
318
    std::atomic<bool> m_scanning_with_passphrase{false};
319
    std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
320
    std::atomic<double> m_scanning_progress{0};
321
    friend class WalletRescanReserver;
322
323
    /** The next scheduled rebroadcast of wallet transactions. */
324
    NodeClock::time_point m_next_resend{GetDefaultNextResend()};
325
    /** Whether this wallet will submit newly created transactions to the node's mempool and
326
     * prompt rebroadcasts (see ResendWalletTransactions()). */
327
    bool fBroadcastTransactions = false;
328
    // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
329
    std::atomic<int64_t> m_best_block_time {0};
330
331
    // First created key time. Used to skip blocks prior to this time.
332
    // 'std::numeric_limits<int64_t>::max()' if wallet is blank.
333
    std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
334
335
    /**
336
     * Used to keep track of spent outpoints, and
337
     * detect and report conflicts (double-spends or
338
     * mutated transactions where the mutant gets mined).
339
     */
340
    typedef std::unordered_multimap<COutPoint, Txid, SaltedOutpointHasher> TxSpends;
341
    TxSpends mapTxSpends GUARDED_BY(cs_wallet);
342
    void AddToSpends(const COutPoint& outpoint, const Txid& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
343
    void AddToSpends(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
344
345
    /**
346
     * Add a transaction to the wallet, or update it.  confirm.block_* should
347
     * be set when the transaction was known to be included in a block.  When
348
     * block_hash.IsNull(), then wallet state is not updated in AddToWallet, but
349
     * notifications happen and cached balances are marked dirty.
350
     *
351
     * TODO: One exception to this is that the abandoned state is cleared under the
352
     * assumption that any further notification of a transaction that was considered
353
     * abandoned is an indication that it is not safe to be considered abandoned.
354
     * Abandoned state should probably be more carefully tracked via different
355
     * chain notifications or by checking mempool presence when necessary.
356
     *
357
     * Should be called with rescanning_old_block set to true, if the transaction is
358
     * not discovered in real time, but during a rescan of old blocks.
359
     */
360
    bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
361
362
    /** Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
363
    void MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx);
364
365
    enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
366
367
    using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
368
369
    /** Mark a transaction (and its in-wallet descendants) as a particular tx state. */
370
    void RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
371
    void RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
372
373
    /** Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
374
    void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
375
376
    void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
377
378
    bool SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
379
380
    /** WalletFlags set on this wallet. */
381
    std::atomic<uint64_t> m_wallet_flags{0};
382
383
    bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& strPurpose);
384
385
    //! Unsets a wallet flag and saves it to disk
386
    void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
387
388
    //! Unset the blank wallet flag and saves it to disk
389
    void UnsetBlankWalletFlag(WalletBatch& batch) override;
390
391
    /** Interface for accessing chain state. */
392
    interfaces::Chain* m_chain;
393
394
    /** Wallet name: relative directory name or "" for default wallet. */
395
    std::string m_name;
396
397
    /** Internal database handle. */
398
    std::unique_ptr<WalletDatabase> m_database;
399
400
    /**
401
     * The following is used to keep track of how far behind the wallet is
402
     * from the chain sync, and to allow clients to block on us being caught up.
403
     *
404
     * Processed hash is a pointer on node's tip and doesn't imply that the wallet
405
     * has scanned sequentially all blocks up to this one.
406
     */
407
    uint256 m_last_block_processed GUARDED_BY(cs_wallet);
408
409
    /** Height of last block processed is used by wallet to know depth of transactions
410
     * without relying on Chain interface beyond asynchronous updates. For safety, we
411
     * initialize it to -1. Height is a pointer on node's tip and doesn't imply
412
     * that the wallet has scanned sequentially all blocks up to this one.
413
     */
414
    int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
415
416
    std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
417
    std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
418
419
    // Indexed by a unique identifier produced by each ScriptPubKeyMan using
420
    // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
421
    std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
422
423
    // Appends spk managers into the main 'm_spk_managers'.
424
    // Must be the only method adding data to it.
425
    void AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man);
426
427
    // Same as 'AddActiveScriptPubKeyMan' but designed for use within a batch transaction context
428
    void AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal);
429
430
    /** Store wallet flags */
431
    void SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags);
432
433
    //! Cache of descriptor ScriptPubKeys used for IsMine. Maps ScriptPubKey to set of spkms
434
    std::unordered_map<CScript, std::vector<ScriptPubKeyMan*>, SaltedSipHasher> m_cached_spks;
435
436
    //! Set of both spent and unspent transaction outputs owned by this wallet
437
    std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher> m_txos GUARDED_BY(cs_wallet);
438
439
    /**
440
     * Catch wallet up to current chain, scanning new blocks, updating the best
441
     * block locator and m_last_block_processed, and registering for
442
     * notifications about new blocks and transactions.
443
     */
444
    static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
445
446
    static NodeClock::time_point GetDefaultNextResend();
447
448
    // Update last block processed in memory only
449
    void SetLastBlockProcessedInMem(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
450
451
    //! Update mempool conflicts for TRUC sibling transactions
452
    void UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
453
454
public:
455
    /**
456
     * Main wallet lock.
457
     * This lock protects all the fields added by CWallet.
458
     */
459
    mutable RecursiveMutex cs_wallet;
460
461
    WalletDatabase& GetDatabase() const override
462
167k
    {
463
167k
        assert(static_cast<bool>(m_database));
464
167k
        return *m_database;
465
167k
    }
466
467
    /** Get a name for this wallet for logging/debugging purposes.
468
     */
469
146k
    const std::string& GetName() const { return m_name; }
470
471
    typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
472
    MasterKeyMap mapMasterKeys;
473
    unsigned int nMasterKeyMaxID = 0;
474
475
    /** Construct wallet with specified name and database implementation. */
476
    CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
477
1.08k
        : m_chain(chain),
478
1.08k
          m_name(name),
479
1.08k
          m_database(std::move(database))
480
1.08k
    {
481
1.08k
    }
482
483
    ~CWallet()
484
1.08k
    {
485
        // Should not have slots connected at this point.
486
1.08k
        assert(NotifyUnload.empty());
487
1.08k
    }
488
489
    bool IsLocked() const override;
490
    bool Lock();
491
492
    /** Interface to assert chain access */
493
8.08k
    bool HaveChain() const { return m_chain ? true : false; }
494
495
    /** Map from txid to CWalletTx for all transactions this wallet is
496
     * interested in, including received and sent transactions. */
497
    std::unordered_map<Txid, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
498
499
    typedef std::multimap<int64_t, CWalletTx*> TxItems;
500
    TxItems wtxOrdered;
501
502
    int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
503
504
    std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
505
    const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
506
507
    /** Set of Coins owned by this wallet that we won't try to spend from. A
508
     * Coin may be locked if it has already been used to fund a transaction
509
     * that hasn't confirmed yet. We wouldn't consider the Coin spent already,
510
     * but also shouldn't try to use it again.
511
     * bool to track whether this locked coin is persisted to disk.
512
     */
513
    std::map<COutPoint, bool> m_locked_coins GUARDED_BY(cs_wallet);
514
515
    /** Registered interfaces::Chain::Notifications handler. */
516
    std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
517
518
    /** Interface for accessing chain state. */
519
1.05M
    interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
520
521
    const CWalletTx* GetWalletTx(const Txid& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
522
523
    std::set<Txid> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
524
525
5.24k
    const std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher>& GetTXOs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return m_txos; };
526
    std::optional<WalletTXO> GetTXO(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
527
528
    /** Cache outputs that belong to the wallet from a single transaction */
529
    void RefreshTXOsFromTx(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
530
    /** Cache outputs that belong to the wallet for all transactions in the wallet */
531
    void RefreshAllTXOs() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
532
533
    /**
534
     * Return depth of transaction in blockchain:
535
     * <0  : conflicts with a transaction this deep in the blockchain
536
     *  0  : in memory pool, waiting to be included in a block
537
     * >=1 : this many blocks deep in the main chain
538
     *
539
     * Preconditions: it is only valid to call this function when the wallet is
540
     * online and the block index is loaded. So this cannot be called by
541
     * bitcoin-wallet tool code or by wallet migration code. If this is called
542
     * without the wallet being online, it won't be able able to determine the
543
     * the height of the last block processed, or the heights of blocks
544
     * referenced in transaction, and might cause assert failures.
545
     */
546
    int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
547
548
    /**
549
     * @return number of blocks to maturity for this transaction:
550
     *  0 : is not a coinbase transaction, or is a mature coinbase transaction
551
     * >0 : is a coinbase transaction which matures in this many blocks
552
     */
553
    int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
554
    bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
555
556
    enum class SpendType {
557
        UNSPENT,
558
        CONFIRMED,
559
        MEMPOOL,
560
        NONMEMPOOL,
561
    };
562
    SpendType HowSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
563
    bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
564
565
    // Whether this or any known scriptPubKey with the same single key has been spent.
566
    bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
567
    void SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
568
569
    /** Display address on an external signer. */
570
    util::Result<void> DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
571
572
    bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
573
    void LoadLockedCoin(const COutPoint& coin, bool persistent) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
574
    bool LockCoin(const COutPoint& output, bool persist) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
575
    bool UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
576
    bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
577
    void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
578
579
    /*
580
     * Rescan abort properties
581
     */
582
3
    void AbortRescan() { fAbortRescan = true; }
583
2.71k
    bool IsAbortingRescan() const { return fAbortRescan; }
584
2.52k
    bool IsScanning() const { return fScanningWallet; }
585
48
    bool IsScanningWithPassphrase() const { return m_scanning_with_passphrase; }
586
0
    SteadyClock::duration ScanningDuration() const { return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
587
0
    double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
588
589
    //! Upgrade DescriptorCaches
590
    void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
591
592
    //! Marks destination as previously spent.
593
    void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
594
    //! Appends payment request to destination.
595
    void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
596
597
    //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
598
    int64_t nRelockTime GUARDED_BY(cs_wallet){0};
599
600
    // Used to prevent concurrent calls to walletpassphrase RPC.
601
    Mutex m_unlock_mutex;
602
    // Used to prevent deleting the passphrase from memory when it is still in use.
603
    RecursiveMutex m_relock_mutex;
604
605
    bool Unlock(const SecureString& strWalletPassphrase);
606
    bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
607
    bool EncryptWallet(const SecureString& strWalletPassphrase);
608
609
    unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
610
611
    /**
612
     * Increment the next transaction order id
613
     * @return next transaction order id
614
     */
615
    int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
616
    DBErrors ReorderTransactions();
617
618
    void MarkDirty();
619
620
    //! Callback for updating transaction metadata in mapWallet.
621
    //!
622
    //! @param wtx - reference to mapWallet transaction to update
623
    //! @param new_tx - true if wtx is newly inserted, false if it previously existed
624
    //!
625
    //! @return true if wtx is changed and needs to be saved to disk, otherwise false
626
    using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
627
628
    /**
629
     * Add the transaction to the wallet, wrapping it up inside a CWalletTx
630
     * @return the recently added wtx pointer or nullptr if there was a db write error.
631
     */
632
    CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool rescanning_old_block = false);
633
    bool LoadToWallet(const Txid& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
634
    void transactionAddedToMempool(const CTransactionRef& tx) override;
635
    void blockConnected(const kernel::ChainstateRole& role, const interfaces::BlockInfo& block) override;
636
    void blockDisconnected(const interfaces::BlockInfo& block) override;
637
    void updatedBlockTip() override;
638
    int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver);
639
640
    struct ScanResult {
641
        enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
642
643
        //! Hash and height of most recent block that was successfully scanned.
644
        //! Unset if no blocks were scanned due to read errors or the chain
645
        //! being empty.
646
        uint256 last_scanned_block;
647
        std::optional<int> last_scanned_height;
648
649
        //! Height of the most recent block that could not be scanned due to
650
        //! read errors or pruning. Will be set if status is FAILURE, unset if
651
        //! status is SUCCESS, and may or may not be set if status is
652
        //! USER_ABORT.
653
        uint256 last_failed_block;
654
    };
655
    ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool save_progress);
656
    void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
657
    /** Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average. */
658
4
    void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
659
    /** Return true if all conditions for periodically resending transactions are met. */
660
    bool ShouldResend() const;
661
    void ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force);
662
663
    OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
664
665
    /** Fetch the inputs and sign with SIGHASH_ALL. */
666
    bool SignTransaction(CMutableTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
667
    /** Sign the tx given the input coins and sighash. */
668
    bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
669
    SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
670
671
    /**
672
     * Fills out a PSBT with information from the wallet. Fills in UTXOs if we have
673
     * them. Tries to sign if options.sign=true.
674
     * Sets `complete` if the PSBT is now complete (i.e. has all required
675
     * signatures or signature-parts, and is ready to finalize.)
676
     *
677
     * @param[in]  psbtx PartiallySignedTransaction to fill in
678
     * @param[in]  options options for filling or signing
679
     * @param[out] complete indicates whether the PSBT is now complete
680
     * @param[out] n_signed the number of inputs signed by this wallet
681
     * @returns an error if something goes wrong
682
     */
683
    std::optional<common::PSBTError> FillPSBT(PartiallySignedTransaction& psbtx,
684
                  const common::PSBTFillOptions& options,
685
                  bool& complete,
686
                  size_t* n_signed = nullptr) const;
687
688
    /**
689
     * Submit the transaction to the node's mempool and then relay to peers.
690
     * Should be called after CreateTransaction unless you want to abort
691
     * broadcasting the transaction.
692
     *
693
     * @param[in] tx The transaction to be broadcast.
694
     * @param[in] replaces_txid The txid of the transaction that this transaction replaces
695
     * @param[in] comment The user's comment for this transaction
696
     * @param[in] comment_to The comment for this transaction indicating where coins are sent to
697
     * @param[in] messages The BIP 21 URI messages to attach to this transaction
698
     */
699
    void CommitTransaction(
700
        CTransactionRef tx,
701
        std::optional<Txid> replaces_txid = std::nullopt,
702
        std::optional<std::string> comment = std::nullopt,
703
        std::optional<std::string> comment_to = std::nullopt,
704
        const std::vector<std::string>& messages = {},
705
        const std::vector<std::string>& payment_requests = {}
706
    );
707
708
    /** Pass this transaction to node for optional mempool insertion and relay to peers. */
709
    bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, node::TxBroadcast broadcast_method) const
710
        EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
711
712
    /** Updates wallet birth time if 'time' is below it */
713
    void MaybeUpdateBirthTime(int64_t time);
714
715
    unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
716
    /** Allow Coin Selection to pick unconfirmed UTXOs that were sent from our own wallet if it
717
     * cannot fund the transaction otherwise. */
718
    bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
719
    bool m_signal_rbf{DEFAULT_WALLET_RBF};
720
    bool m_allow_fallback_fee{true}; //!< will be false if -fallbackfee=0
721
    CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE};
722
    /**
723
     * If fee estimation does not have enough data to provide estimates, use this fee instead.
724
     * Has no effect if not using fee estimation
725
     * Override with -fallbackfee
726
     */
727
    CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
728
729
     /** If the cost to spend a change output at this feerate is greater than the value of the
730
      * output itself, just drop it to fees. */
731
    CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
732
733
    /** When the actual feerate is less than the consolidate feerate, we will tend to make transactions which
734
     * consolidate inputs. When the actual feerate is greater than the consolidate feerate, we will tend to make
735
     * transactions which have the lowest fees.
736
     */
737
    CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
738
739
    /** The maximum fee amount we're willing to pay to prioritize partial spend avoidance. */
740
    CAmount m_max_aps_fee{DEFAULT_MAX_AVOIDPARTIALSPEND_FEE}; //!< note: this is absolute fee, not fee rate
741
    OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
742
    /**
743
     * Default output type for change outputs. When unset, automatically choose type
744
     * based on address type setting and the types other of non-change outputs
745
     * (see -changetype option documentation and implementation in
746
     * CWallet::TransactionChangeType for details).
747
     */
748
    std::optional<OutputType> m_default_change_type{};
749
    /** Absolute maximum transaction fee (in satoshis) used by default for the wallet */
750
    CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
751
752
    /** Number of pre-generated keys/scripts by each spkm (part of the look-ahead process, used to detect payments) */
753
    int64_t m_keypool_size{DEFAULT_KEYPOOL_SIZE};
754
755
    /** Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify) */
756
    std::string m_notify_tx_changed_script;
757
758
    size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
759
    bool TopUpKeyPool(unsigned int kpSize = 0);
760
761
    // Filter struct for 'ListAddrBookAddresses'
762
    struct AddrBookFilter {
763
        // Fetch addresses with the provided label
764
        std::optional<std::string> m_op_label{std::nullopt};
765
        // Don't include change addresses by default
766
        bool ignore_change{true};
767
    };
768
769
    /**
770
     * Filter and retrieve destinations stored in the addressbook
771
     */
772
    std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
773
774
    /**
775
     * Retrieve all the known labels in the address book
776
     */
777
    std::set<std::string> ListAddrBookLabels(std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
778
779
    /**
780
     * Walk-through the address book entries.
781
     * Stops when the provided 'ListAddrBookFunc' returns false.
782
     */
783
    using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
784
    void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
785
786
    /**
787
     * Marks all outputs in each one of the destinations dirty, so their cache is
788
     * reset and does not return outdated information.
789
     */
790
    void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
791
792
    util::Result<CTxDestination> GetNewDestination(OutputType type, const std::string& label);
793
    util::Result<CTxDestination> GetNewChangeDestination(OutputType type);
794
795
    bool IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
796
    bool IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
797
    /** Returns amount of debit, i.e. the amount leaving this wallet due to this input */
798
    CAmount GetDebit(const CTxIn& txin) const;
799
    bool IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
800
    bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
801
    bool IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
802
    /** should probably be renamed to IsRelevantToMe */
803
    bool IsFromMe(const CTransaction& tx) const;
804
    CAmount GetDebit(const CTransaction& tx) const;
805
806
    DBErrors PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings);
807
808
    /** Erases the provided transactions from the wallet. */
809
    util::Result<void> RemoveTxs(std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810
    util::Result<void> RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
811
812
    bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
813
814
    bool DelAddressBook(const CTxDestination& address);
815
    bool DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address);
816
817
    bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
818
    bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
819
820
    std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
821
    bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
822
    bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
823
824
    unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
825
826
    //! Get wallet transactions that conflict with given transaction (spend same outputs)
827
    std::set<Txid> GetConflicts(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
828
829
    //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
830
    bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
831
832
    //! Close wallet database
833
    void Close();
834
835
    /** Wallet is about to be unloaded */
836
    btcsignals::signal<void ()> NotifyUnload;
837
838
    /**
839
     * Address book entry changed.
840
     * @note called without lock cs_wallet held.
841
     */
842
    btcsignals::signal<void(const CTxDestination& address,
843
                                 const std::string& label, bool isMine,
844
                                 AddressPurpose purpose, ChangeType status)>
845
        NotifyAddressBookChanged;
846
847
    /**
848
     * Wallet transaction added, removed or updated.
849
     * @note called with lock cs_wallet held.
850
     */
851
    btcsignals::signal<void(const Txid& hashTx, ChangeType status)> NotifyTransactionChanged;
852
853
    /** Show progress e.g. for rescan */
854
    btcsignals::signal<void (const std::string &title, int nProgress)> ShowProgress;
855
856
    /** Keypool has new keys */
857
    btcsignals::signal<void ()> NotifyCanGetAddressesChanged;
858
859
    /**
860
     * Wallet status (encrypted, locked) changed.
861
     * Note: Called without locks held.
862
     */
863
    btcsignals::signal<void (CWallet* wallet)> NotifyStatusChanged;
864
865
    /** Inquire whether this wallet broadcasts transactions. */
866
1.68k
    bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
867
    /** Set whether this wallet broadcasts transactions. */
868
999
    void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
869
870
    /** Return whether transaction can be abandoned */
871
    bool TransactionCanBeAbandoned(const Txid& hashTx) const;
872
873
    /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
874
    bool AbandonTransaction(const Txid& hashTx);
875
    bool AbandonTransaction(CWalletTx& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
876
877
    /** Mark a transaction as replaced by another transaction. */
878
    bool MarkReplaced(const Txid& originalHash, const Txid& newHash);
879
880
    static bool LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings);
881
882
    /* Initializes, creates and returns a new CWallet; returns a null pointer in case of an error */
883
    static std::shared_ptr<CWallet> CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bool born_encrypted, bilingual_str& error, std::vector<bilingual_str>& warnings);
884
885
    /* Initializes, loads, and returns a CWallet from an existing wallet; returns a null pointer in case of an error */
886
    static std::shared_ptr<CWallet> LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings);
887
888
    /**
889
     * Wallet post-init setup
890
     * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
891
     */
892
    void postInitProcess();
893
894
    [[nodiscard]] bool BackupWallet(const std::string& strDest) const;
895
896
    /* Returns true if HD is enabled */
897
    bool IsHDEnabled() const;
898
899
    /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
900
    bool CanGetAddresses(bool internal = false) const;
901
902
    /* Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction */
903
432
    int64_t GetBirthTime() const { return m_birth_time; }
904
905
    /**
906
     * Blocks until the wallet state is up-to-date to /at least/ the current
907
     * chain at the time this function is entered
908
     * Obviously holding cs_main/cs_wallet when going into this call may cause
909
     * deadlock
910
     */
911
    void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
912
913
    /** set a single wallet flag */
914
    void SetWalletFlag(uint64_t flags);
915
916
    /** Unsets a single wallet flag */
917
    void UnsetWalletFlag(uint64_t flag);
918
919
    /** check if a certain wallet flag is set */
920
    bool IsWalletFlagSet(uint64_t flag) const override;
921
922
    /** overwrite all flags by the given uint64_t
923
       flags must be uninitialised (or 0)
924
       only known flags may be present */
925
    void InitWalletFlags(uint64_t flags);
926
    /** Loads the flags into the wallet. (used by LoadWallet) */
927
    bool LoadWalletFlags(uint64_t flags);
928
    //! Retrieve all of the wallet's flags
929
    uint64_t GetWalletFlags() const;
930
931
    /** Return wallet name for use in logs, will return "default wallet" if the wallet has no name. */
932
    std::string LogName() const override
933
53.9k
    {
934
53.9k
        std::string name{GetName()};
935
53.9k
        return name.empty() ? "default wallet" : name;
936
53.9k
    };
937
938
    /** Return wallet name for display, like LogName() but translates "default wallet" string. */
939
    std::string DisplayName() const
940
2.28k
    {
941
2.28k
        std::string name{GetName()};
942
2.28k
        return name.empty() ? _("default wallet") : name;
943
2.28k
    };
944
945
    /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
946
    template <typename... Params>
947
    void WalletLogPrintf(util::ConstevalFormatString<sizeof...(Params)> wallet_fmt, const Params&... params) const
948
53.4k
    {
949
53.4k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
53.4k
    };
void wallet::CWallet::WalletLogPrintf<unsigned int>(util::ConstevalFormatString<sizeof...(unsigned int)>, unsigned int const&) const
Line
Count
Source
948
982
    {
949
982
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
982
    };
void wallet::CWallet::WalletLogPrintf<unsigned long>(util::ConstevalFormatString<sizeof...(unsigned long)>, unsigned long const&) const
Line
Count
Source
948
1.91k
    {
949
1.91k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
1.91k
    };
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) const
Line
Count
Source
948
1.02k
    {
949
1.02k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
1.02k
    };
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, long>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, long)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, long const&) const
Line
Count
Source
948
3.56k
    {
949
3.56k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
3.56k
    };
void wallet::CWallet::WalletLogPrintf<long, int, int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double>(util::ConstevalFormatString<sizeof...(long, int, int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double)>, long const&, int const&, int const&, int const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&) const
Line
Count
Source
948
3.56k
    {
949
3.56k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
3.56k
    };
void wallet::CWallet::WalletLogPrintf<long, long, char const*>(util::ConstevalFormatString<sizeof...(long, long, char const*)>, long const&, long const&, char const* const&) const
Line
Count
Source
948
1.74k
    {
949
1.74k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
1.74k
    };
Unexecuted instantiation: void wallet::CWallet::WalletLogPrintf<char [13], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(char [13], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, char const (&) [13], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) const
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) const
Line
Count
Source
948
25.9k
    {
949
25.9k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
25.9k
    };
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, unsigned int>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, unsigned int)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, unsigned int const&) const
Line
Count
Source
948
215
    {
949
215
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
215
    };
void wallet::CWallet::WalletLogPrintf<char [15], int>(util::ConstevalFormatString<sizeof...(char [15], int)>, char const (&) [15], int const&) const
Line
Count
Source
948
622
    {
949
622
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
622
    };
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, char const* const&) const
Line
Count
Source
948
2.38k
    {
949
2.38k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
2.38k
    };
void wallet::CWallet::WalletLogPrintf<int, double>(util::ConstevalFormatString<sizeof...(int, double)>, int const&, double const&) const
Line
Count
Source
948
4
    {
949
4
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
4
    };
void wallet::CWallet::WalletLogPrintf<int>(util::ConstevalFormatString<sizeof...(int)>, int const&) const
Line
Count
Source
948
370
    {
949
370
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
370
    };
void wallet::CWallet::WalletLogPrintf<>(util::ConstevalFormatString<sizeof...()>) const
Line
Count
Source
948
818
    {
949
818
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
818
    };
void wallet::CWallet::WalletLogPrintf<long>(util::ConstevalFormatString<sizeof...(long)>, long const&) const
Line
Count
Source
948
1.69k
    {
949
1.69k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
1.69k
    };
void wallet::CWallet::WalletLogPrintf<char [27], int>(util::ConstevalFormatString<sizeof...(char [27], int)>, char const (&) [27], int const&) const
Line
Count
Source
948
60
    {
949
60
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
60
    };
void wallet::CWallet::WalletLogPrintf<std::basic_string_view<char, std::char_traits<char>>>(util::ConstevalFormatString<sizeof...(std::basic_string_view<char, std::char_traits<char>>)>, std::basic_string_view<char, std::char_traits<char>> const&) const
Line
Count
Source
948
1.54k
    {
949
1.54k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
1.54k
    };
Unexecuted instantiation: void wallet::CWallet::WalletLogPrintf<char [21], char [42]>(util::ConstevalFormatString<sizeof...(char [21], char [42])>, char const (&) [21], char const (&) [42]) const
Unexecuted instantiation: void wallet::CWallet::WalletLogPrintf<char [17], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(char [17], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, char const (&) [17], std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) const
void wallet::CWallet::WalletLogPrintf<int, int>(util::ConstevalFormatString<sizeof...(int, int)>, int const&, int const&) const
Line
Count
Source
948
62
    {
949
62
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
62
    };
void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, char const* const&) const
Line
Count
Source
948
6.44k
    {
949
6.44k
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
6.44k
    };
void wallet::CWallet::WalletLogPrintf<int, int, int, int>(util::ConstevalFormatString<sizeof...(int, int, int, int)>, int const&, int const&, int const&, int const&) const
Line
Count
Source
948
426
    {
949
426
        LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
950
426
    };
Unexecuted instantiation: void wallet::CWallet::WalletLogPrintf<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) const
Unexecuted instantiation: void wallet::CWallet::WalletLogPrintf<char const*>(util::ConstevalFormatString<sizeof...(char const*)>, char const* const&) const
951
952
    void LogStats() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
953
955
    {
954
955
        AssertLockHeld(cs_wallet);
955
955
        WalletLogPrintf("setKeyPool.size() = %u\n",      GetKeyPoolSize());
956
955
        WalletLogPrintf("mapWallet.size() = %u\n",       mapWallet.size());
957
955
        WalletLogPrintf("m_address_book.size() = %u\n",  m_address_book.size());
958
955
    };
959
960
    //! Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers
961
    std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
962
    bool IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const;
963
964
    //! Returns all unique ScriptPubKeyMans
965
    std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
966
967
    //! Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
968
    ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
969
970
    //! Get all the ScriptPubKeyMans for a script
971
    std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
972
    //! Get the ScriptPubKeyMan by id
973
    ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
974
975
    //! Get the SigningProvider for a script
976
    std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
977
    std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
978
979
    //! Get the wallet descriptors for a script.
980
    std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
981
982
    //! Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
983
    LegacyDataSPKM* GetLegacyDataSPKM() const;
984
    LegacyDataSPKM* GetOrCreateLegacyDataSPKM();
985
986
    //! Make a Legacy(Data)SPKM and set it for all types, internal, and external.
987
    void SetupLegacyScriptPubKeyMan();
988
989
    bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const override;
990
991
    bool HasEncryptionKeys() const override;
992
    bool HaveCryptedKeys() const;
993
994
    /** Get last block processed height */
995
    int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
996
1.22M
    {
997
1.22M
        AssertLockHeld(cs_wallet);
998
1.22M
        assert(m_last_block_processed_height >= 0);
999
1.22M
        return m_last_block_processed_height;
1000
1.22M
    };
1001
    uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1002
85.4k
    {
1003
85.4k
        AssertLockHeld(cs_wallet);
1004
85.4k
        assert(m_last_block_processed_height >= 0);
1005
85.4k
        return m_last_block_processed;
1006
85.4k
    }
1007
    /** Set last block processed height, and write to database */
1008
    void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1009
    /** Write the current best block to database */
1010
    void WriteBestBlock() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1011
1012
    //! Connect the signals from ScriptPubKeyMans to the signals in CWallet
1013
    void ConnectScriptPubKeyManNotifiers();
1014
1015
    //! Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it
1016
    void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc, const KeyMap& keys, const CryptedKeyMap& ckeys);
1017
1018
    //! Adds the active ScriptPubKeyMan for the specified type and internal. Writes it to the wallet file
1019
    //! @param[in] id The unique id for the ScriptPubKeyMan
1020
    //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1021
    //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1022
    void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1023
1024
    //! Loads an active ScriptPubKeyMan for the specified type and internal. (used by LoadWallet)
1025
    //! @param[in] id The unique id for the ScriptPubKeyMan
1026
    //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1027
    //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1028
    void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1029
1030
    //! Remove specified ScriptPubKeyMan from set of active SPK managers. Writes the change to the wallet file.
1031
    //! @param[in] id The unique id for the ScriptPubKeyMan
1032
    //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1033
    //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1034
    void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1035
1036
    //! Create new DescriptorScriptPubKeyMan and add it to the wallet
1037
    DescriptorScriptPubKeyMan& SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1038
    //! Create new DescriptorScriptPubKeyMans and add them to the wallet
1039
    void SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1040
    void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1041
1042
    //! Create new seed and default DescriptorScriptPubKeyMans for this wallet
1043
    void SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1044
1045
    //! Setup new descriptors or seed for new address generation
1046
    void SetupWalletGeneration() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1047
1048
    //! Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet
1049
    DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1050
1051
    //! Returns whether the provided ScriptPubKeyMan is internal
1052
    //! @param[in] spk_man The ScriptPubKeyMan to test
1053
    //! @return contains value only for active DescriptorScriptPubKeyMan, otherwise undefined
1054
    std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1055
1056
    //! Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type
1057
    util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1058
1059
    /** Move all records from the BDB database to a new SQLite database for storage.
1060
     * The original BDB file will be deleted and replaced with a new SQLite file.
1061
     * A backup is not created.
1062
     * May crash if something unexpected happens in the filesystem.
1063
     */
1064
    bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1065
1066
    //! Get all of the descriptors from a legacy wallet
1067
    std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1068
1069
    //! Adds the ScriptPubKeyMans given in MigrationData to this wallet, removes LegacyScriptPubKeyMan,
1070
    //! and where needed, moves tx and address book entries to watchonly_wallet or solvable_wallet
1071
    util::Result<void> ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1072
1073
    //! Whether the (external) signer performs R-value signature grinding
1074
    bool CanGrindR() const;
1075
1076
    //! Add scriptPubKeys for this ScriptPubKeyMan into the scriptPubKey cache
1077
    void CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm);
1078
1079
    void TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm) override;
1080
1081
    //! Retrieve the xpubs in use by the active descriptors
1082
    std::set<CExtPubKey> GetActiveHDPubKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1083
1084
    //! Find the private key for the given key id from the wallet's descriptors, if available
1085
    //! Returns nullopt when no descriptor has the key or if the wallet is locked.
1086
    std::optional<CKey> GetKey(const CKeyID& keyid) const;
1087
1088
    //! Disconnect chain notifications and wait for all notifications to be processed
1089
    void DisconnectChainNotifications();
1090
};
1091
1092
/**
1093
 * Called periodically by the schedule thread. Prompts individual wallets to resend
1094
 * their transactions. Actual rebroadcast schedule is managed by the wallets themselves.
1095
 */
1096
void MaybeResendWalletTxs(WalletContext& context);
1097
1098
/** RAII object to check and reserve a wallet rescan */
1099
class WalletRescanReserver
1100
{
1101
private:
1102
    using Clock = std::chrono::steady_clock;
1103
    using NowFn = std::function<Clock::time_point()>;
1104
    CWallet& m_wallet;
1105
    bool m_could_reserve{false};
1106
    NowFn m_now;
1107
public:
1108
1.05k
    explicit WalletRescanReserver(CWallet& w) : m_wallet(w) {}
1109
1110
    bool reserve(bool with_passphrase = false)
1111
1.05k
    {
1112
1.05k
        assert(!m_could_reserve);
1113
1.05k
        if (m_wallet.fScanningWallet.exchange(true)) {
1114
1
            return false;
1115
1
        }
1116
        // Discard any abort request left over from previous reservation, so
1117
        // that an abort requested while the reservation is held always applies
1118
        // to abort this rescan, even if it arrives before the scan loop starts.
1119
1.05k
        m_wallet.fAbortRescan = false;
1120
1.05k
        m_wallet.m_scanning_with_passphrase.exchange(with_passphrase);
1121
1.05k
        m_wallet.m_scanning_start = SteadyClock::now();
1122
1.05k
        m_wallet.m_scanning_progress = 0;
1123
1.05k
        m_could_reserve = true;
1124
1.05k
        return true;
1125
1.05k
    }
1126
1127
    bool isReserved() const
1128
703
    {
1129
703
        return (m_could_reserve && m_wallet.fScanningWallet);
1130
703
    }
1131
1132
82.3k
    Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
1133
1134
1
    void setNow(NowFn now) { m_now = std::move(now); }
1135
1136
    ~WalletRescanReserver()
1137
1.05k
    {
1138
1.05k
        if (m_could_reserve) {
1139
1.05k
            m_wallet.fScanningWallet = false;
1140
1.05k
            m_wallet.m_scanning_with_passphrase = false;
1141
1.05k
        }
1142
1.05k
    }
1143
};
1144
1145
//! Add wallet name to persistent configuration so it will be loaded on startup.
1146
bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1147
1148
//! Remove wallet name from persistent configuration so it will not be loaded on startup.
1149
bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1150
1151
struct MigrationResult {
1152
    std::string wallet_name;
1153
    std::optional<std::string> watchonly_wallet_name;
1154
    std::optional<std::string> solvables_wallet_name;
1155
    std::shared_ptr<CWallet> wallet;
1156
    std::shared_ptr<CWallet> watchonly_wallet;
1157
    std::shared_ptr<CWallet> solvables_wallet;
1158
    fs::path backup_path;
1159
};
1160
1161
//! Do all steps to migrate a legacy wallet to a descriptor wallet
1162
[[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context, bool load_wallet = true);
1163
//! Requirement: The wallet provided to this function must be isolated, with no attachment to the node's context.
1164
[[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context, bool load_wallet = true);
1165
1166
//! Determine the path that the wallet is stored in
1167
util::Result<fs::path> GetWalletPath(const std::string& name);
1168
} // namespace wallet
1169
1170
#endif // BITCOIN_WALLET_WALLET_H