Coverage Report

Created: 2026-11-13 17:38

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