Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/wallet.cpp
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
#include <wallet/wallet.h>
7
8
#include <bitcoin-build-config.h> // IWYU pragma: keep
9
#include <addresstype.h>
10
#include <blockfilter.h>
11
#include <chain.h>
12
#include <coins.h>
13
#include <common/args.h>
14
#include <common/messages.h>
15
#include <common/settings.h>
16
#include <common/signmessage.h>
17
#include <common/system.h>
18
#include <consensus/amount.h>
19
#include <consensus/consensus.h>
20
#include <consensus/validation.h>
21
#include <external_signer.h>
22
#include <interfaces/chain.h>
23
#include <interfaces/handler.h>
24
#include <interfaces/wallet.h>
25
#include <kernel/mempool_removal_reason.h>
26
#include <kernel/types.h>
27
#include <key.h>
28
#include <key_io.h>
29
#include <logging.h>
30
#include <node/types.h>
31
#include <outputtype.h>
32
#include <policy/feerate.h>
33
#include <policy/truc_policy.h>
34
#include <primitives/block.h>
35
#include <primitives/transaction.h>
36
#include <psbt.h>
37
#include <pubkey.h>
38
#include <random.h>
39
#include <script/descriptor.h>
40
#include <script/interpreter.h>
41
#include <script/script.h>
42
#include <script/sign.h>
43
#include <script/signingprovider.h>
44
#include <script/solver.h>
45
#include <serialize.h>
46
#include <span.h>
47
#include <streams.h>
48
#include <support/allocators/secure.h>
49
#include <support/allocators/zeroafterfree.h>
50
#include <support/cleanse.h>
51
#include <sync.h>
52
#include <tinyformat.h>
53
#include <uint256.h>
54
#include <univalue.h>
55
#include <util/check.h>
56
#include <util/fs.h>
57
#include <util/fs_helpers.h>
58
#include <util/moneystr.h>
59
#include <util/result.h>
60
#include <util/string.h>
61
#include <util/time.h>
62
#include <util/translation.h>
63
#include <wallet/coincontrol.h>
64
#include <wallet/context.h>
65
#include <wallet/crypter.h>
66
#include <wallet/db.h>
67
#include <wallet/external_signer_scriptpubkeyman.h>
68
#include <wallet/scriptpubkeyman.h>
69
#include <wallet/transaction.h>
70
#include <wallet/types.h>
71
#include <wallet/walletdb.h>
72
#include <wallet/walletutil.h>
73
74
#include <algorithm>
75
#include <cassert>
76
#include <condition_variable>
77
#include <exception>
78
#include <optional>
79
#include <stdexcept>
80
#include <thread>
81
#include <tuple>
82
#include <variant>
83
84
struct KeyOriginInfo;
85
86
using common::AmountErrMsg;
87
using common::AmountHighWarn;
88
using common::PSBTError;
89
using interfaces::FoundBlock;
90
using kernel::ChainstateRole;
91
using util::ReplaceAll;
92
using util::ToString;
93
94
namespace wallet {
95
96
bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
97
179
{
98
179
    const auto update_function = [&wallet_name](common::SettingsValue& setting_value) {
99
179
        if (!setting_value.isArray()) setting_value.setArray();
100
195
        for (const auto& value : setting_value.getValues()) {
101
195
            if (value.isStr() && value.get_str() == wallet_name) return interfaces::SettingsAction::SKIP_WRITE;
102
195
        }
103
179
        setting_value.push_back(wallet_name);
104
179
        return interfaces::SettingsAction::WRITE;
105
179
    };
106
179
    return chain.updateRwSetting("wallet", update_function);
107
179
}
108
109
bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
110
15
{
111
15
    const auto update_function = [&wallet_name](common::SettingsValue& setting_value) {
112
15
        if (!setting_value.isArray()) return interfaces::SettingsAction::SKIP_WRITE;
113
13
        common::SettingsValue new_value(common::SettingsValue::VARR);
114
34
        for (const auto& value : setting_value.getValues()) {
115
34
            if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
116
34
        }
117
13
        if (new_value.size() == setting_value.size()) return interfaces::SettingsAction::SKIP_WRITE;
118
9
        setting_value = std::move(new_value);
119
9
        return interfaces::SettingsAction::WRITE;
120
13
    };
121
15
    return chain.updateRwSetting("wallet", update_function);
122
15
}
123
124
static void UpdateWalletSetting(interfaces::Chain& chain,
125
                                const std::string& wallet_name,
126
                                std::optional<bool> load_on_startup,
127
                                std::vector<bilingual_str>& warnings)
128
1.67k
{
129
1.67k
    if (!load_on_startup) return;
130
184
    if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
131
0
        warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
132
184
    } else if (!load_on_startup.value() && !RemoveWalletSetting(chain, wallet_name)) {
133
0
        warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
134
0
    }
135
184
}
136
137
/**
138
 * Refresh mempool status so the wallet is in an internally consistent state and
139
 * immediately knows the transaction's status: Whether it can be considered
140
 * trusted and is eligible to be abandoned ...
141
 */
142
static void RefreshMempoolStatus(CWalletTx& tx, interfaces::Chain& chain)
143
17.3k
{
144
17.3k
    if (chain.isInMempool(tx.GetHash())) {
145
3.70k
        tx.m_state = TxStateInMempool();
146
13.6k
    } else if (tx.state<TxStateInMempool>()) {
147
297
        tx.m_state = TxStateInactive();
148
297
    }
149
17.3k
}
150
151
bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
152
872
{
153
872
    LOCK(context.wallets_mutex);
154
872
    assert(wallet);
155
872
    std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
156
872
    if (i != context.wallets.end()) return false;
157
872
    context.wallets.push_back(wallet);
158
872
    wallet->ConnectScriptPubKeyManNotifiers();
159
872
    wallet->NotifyCanGetAddressesChanged();
160
872
    return true;
161
872
}
162
163
bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
164
872
{
165
872
    assert(wallet);
166
167
872
    interfaces::Chain& chain = wallet->chain();
168
872
    std::string name = wallet->GetName();
169
872
    WITH_LOCK(wallet->cs_wallet, wallet->WriteBestBlock());
170
171
    // Unregister with the validation interface which also drops shared pointers.
172
872
    wallet->DisconnectChainNotifications();
173
872
    {
174
872
        LOCK(context.wallets_mutex);
175
872
        std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
176
872
        if (i == context.wallets.end()) return false;
177
872
        context.wallets.erase(i);
178
872
    }
179
    // Notify unload so that upper layers release the shared pointer.
180
0
    wallet->NotifyUnload();
181
182
    // Write the wallet setting
183
872
    UpdateWalletSetting(chain, name, load_on_start, warnings);
184
185
872
    return true;
186
872
}
187
188
bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
189
0
{
190
0
    std::vector<bilingual_str> warnings;
191
0
    return RemoveWallet(context, wallet, load_on_start, warnings);
192
0
}
193
194
std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context)
195
1.27k
{
196
1.27k
    LOCK(context.wallets_mutex);
197
1.27k
    return context.wallets;
198
1.27k
}
199
200
std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count)
201
4.76k
{
202
4.76k
    LOCK(context.wallets_mutex);
203
4.76k
    count = context.wallets.size();
204
4.76k
    return count == 1 ? context.wallets[0] : nullptr;
205
4.76k
}
206
207
std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name)
208
14.9k
{
209
14.9k
    LOCK(context.wallets_mutex);
210
69.1k
    for (const std::shared_ptr<CWallet>& wallet : context.wallets) {
211
69.1k
        if (wallet->GetName() == name) return wallet;
212
69.1k
    }
213
63
    return nullptr;
214
14.9k
}
215
216
std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet)
217
1
{
218
1
    LOCK(context.wallets_mutex);
219
1
    auto it = context.wallet_load_fns.emplace(context.wallet_load_fns.end(), std::move(load_wallet));
220
1
    return interfaces::MakeCleanupHandler([&context, it] { LOCK(context.wallets_mutex); context.wallet_load_fns.erase(it); });
221
1
}
222
223
void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
224
877
{
225
877
    LOCK(context.wallets_mutex);
226
877
    for (auto& load_wallet : context.wallet_load_fns) {
227
1
        load_wallet(interfaces::MakeWallet(context, wallet));
228
1
    }
229
877
}
230
231
static GlobalMutex g_loading_wallet_mutex;
232
static GlobalMutex g_wallet_release_mutex;
233
static std::condition_variable g_wallet_release_cv;
234
static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
235
static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
236
237
// Custom deleter for shared_ptr<CWallet>.
238
static void FlushAndDeleteWallet(CWallet* wallet)
239
954
{
240
954
    const std::string name = wallet->GetName();
241
954
    wallet->WalletLogPrintf("Releasing wallet %s..\n", name);
242
954
    delete wallet;
243
    // Wallet is now released, notify WaitForDeleteWallet, if any.
244
954
    {
245
954
        LOCK(g_wallet_release_mutex);
246
954
        if (g_unloading_wallet_set.erase(name) == 0) {
247
            // WaitForDeleteWallet was not called for this wallet, all done.
248
77
            return;
249
77
        }
250
954
    }
251
877
    g_wallet_release_cv.notify_all();
252
877
}
253
254
void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet)
255
877
{
256
    // Mark wallet for unloading.
257
877
    const std::string name = wallet->GetName();
258
877
    {
259
877
        LOCK(g_wallet_release_mutex);
260
877
        g_unloading_wallet_set.insert(name);
261
        // Do not expect to be the only one removing this wallet.
262
        // Multiple threads could simultaneously be waiting for deletion.
263
877
    }
264
265
    // Time to ditch our shared_ptr and wait for FlushAndDeleteWallet call.
266
877
    wallet.reset();
267
877
    {
268
877
        WAIT_LOCK(g_wallet_release_mutex, lock);
269
877
        while (g_unloading_wallet_set.contains(name)) {
270
0
            g_wallet_release_cv.wait(lock);
271
0
        }
272
877
    }
273
877
}
274
275
namespace {
276
std::shared_ptr<CWallet> LoadWalletInternal(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)
277
233
{
278
233
    try {
279
233
        std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
280
233
        if (!database) {
281
19
            error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
282
19
            return nullptr;
283
19
        }
284
285
214
        context.chain->initMessage(_("Loading wallet…"));
286
214
        std::shared_ptr<CWallet> wallet = CWallet::LoadExisting(context, name, std::move(database), error, warnings);
287
214
        if (!wallet) {
288
10
            error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
289
10
            status = DatabaseStatus::FAILED_LOAD;
290
10
            return nullptr;
291
10
        }
292
293
204
        NotifyWalletLoaded(context, wallet);
294
204
        AddWallet(context, wallet);
295
204
        wallet->postInitProcess();
296
297
        // Write the wallet setting
298
204
        UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
299
300
204
        return wallet;
301
214
    } catch (const std::runtime_error& e) {
302
0
        error = Untranslated(e.what());
303
0
        status = DatabaseStatus::FAILED_LOAD;
304
0
        return nullptr;
305
0
    }
306
233
}
307
308
class FastWalletRescanFilter
309
{
310
public:
311
4
    FastWalletRescanFilter(const CWallet& wallet) : m_wallet(wallet)
312
4
    {
313
        // create initial filter with scripts from all ScriptPubKeyMans
314
36
        for (auto spkm : m_wallet.GetAllScriptPubKeyMans()) {
315
36
            auto desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};
316
36
            assert(desc_spkm != nullptr);
317
36
            AddScriptPubKeys(desc_spkm);
318
            // save each range descriptor's end for possible future filter updates
319
36
            if (desc_spkm->IsHDEnabled()) {
320
32
                m_last_range_ends.emplace(desc_spkm->GetID(), desc_spkm->GetEndRange());
321
32
            }
322
36
        }
323
4
    }
324
325
    void UpdateIfNeeded()
326
615
    {
327
        // repopulate filter with new scripts if top-up has happened since last iteration
328
4.92k
        for (const auto& [desc_spkm_id, last_range_end] : m_last_range_ends) {
329
4.92k
            auto desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(m_wallet.GetScriptPubKeyMan(desc_spkm_id))};
330
4.92k
            assert(desc_spkm != nullptr);
331
4.92k
            int32_t current_range_end{desc_spkm->GetEndRange()};
332
4.92k
            if (current_range_end > last_range_end) {
333
64
                AddScriptPubKeys(desc_spkm, last_range_end);
334
64
                m_last_range_ends.at(desc_spkm->GetID()) = current_range_end;
335
64
            }
336
4.92k
        }
337
615
    }
338
339
    std::optional<bool> MatchesBlock(const uint256& block_hash) const
340
615
    {
341
615
        return m_wallet.chain().blockFilterMatchesAny(BlockFilterType::BASIC, block_hash, m_filter_set);
342
615
    }
343
344
private:
345
    const CWallet& m_wallet;
346
    /** Map for keeping track of each range descriptor's last seen end range.
347
      * This information is used to detect whether new addresses were derived
348
      * (that is, if the current end range is larger than the saved end range)
349
      * after processing a block and hence a filter set update is needed to
350
      * take possible keypool top-ups into account.
351
      */
352
    std::map<uint256, int32_t> m_last_range_ends;
353
    GCSFilter::ElementSet m_filter_set;
354
355
    void AddScriptPubKeys(const DescriptorScriptPubKeyMan* desc_spkm, int32_t last_range_end = 0)
356
100
    {
357
9.60k
        for (const auto& script_pub_key : desc_spkm->GetScriptPubKeys(last_range_end)) {
358
9.60k
            m_filter_set.emplace(script_pub_key.begin(), script_pub_key.end());
359
9.60k
        }
360
100
    }
361
};
362
} // namespace
363
364
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)
365
235
{
366
235
    auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
367
235
    if (!result.second) {
368
2
        error = Untranslated("Wallet already loading.");
369
2
        status = DatabaseStatus::FAILED_LOAD;
370
2
        return nullptr;
371
2
    }
372
233
    auto wallet = LoadWalletInternal(context, name, load_on_start, options, status, error, warnings);
373
233
    WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
374
233
    return wallet;
375
235
}
376
377
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)
378
593
{
379
    // Wallet must have a non-empty name
380
593
    if (name.empty()) {
381
2
        error = Untranslated("Wallet name cannot be empty");
382
2
        status = DatabaseStatus::FAILED_NEW_UNNAMED;
383
2
        return nullptr;
384
2
    }
385
386
591
    uint64_t wallet_creation_flags = options.create_flags;
387
591
    const SecureString& passphrase = options.create_passphrase;
388
389
    // Only descriptor wallets can be created
390
591
    Assert(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS);
391
591
    options.require_format = DatabaseFormat::SQLITE;
392
393
    // Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
394
591
    bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
395
396
    // Born encrypted wallets need to be created blank first.
397
591
    if (!passphrase.empty()) {
398
12
        wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
399
12
    }
400
401
    // Private keys must be disabled for an external signer wallet
402
591
    if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
403
1
        error = Untranslated("Private keys must be disabled when using an external signer");
404
1
        status = DatabaseStatus::FAILED_CREATE;
405
1
        return nullptr;
406
1
    }
407
408
    // Do not allow a passphrase when private keys are disabled
409
590
    if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
410
4
        error = Untranslated("Passphrase provided but private keys are disabled. A passphrase is only used to encrypt private keys, so cannot be used for wallets with private keys disabled.");
411
4
        status = DatabaseStatus::FAILED_CREATE;
412
4
        return nullptr;
413
4
    }
414
415
    // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
416
586
    std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
417
586
    if (!database) {
418
4
        error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
419
4
        status = DatabaseStatus::FAILED_VERIFY;
420
4
        return nullptr;
421
4
    }
422
423
    // Make the wallet
424
582
    context.chain->initMessage(_("Creating wallet…"));
425
582
    std::shared_ptr<CWallet> wallet = CWallet::CreateNew(context, name, std::move(database), wallet_creation_flags, error, warnings);
426
582
    if (!wallet) {
427
0
        error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
428
0
        status = DatabaseStatus::FAILED_CREATE;
429
0
        return nullptr;
430
0
    }
431
432
    // Encrypt the wallet
433
582
    if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
434
8
        if (!wallet->EncryptWallet(passphrase)) {
435
0
            error = Untranslated("Error: Wallet created but failed to encrypt.");
436
0
            status = DatabaseStatus::FAILED_ENCRYPT;
437
0
            return nullptr;
438
0
        }
439
8
        if (!create_blank) {
440
            // Unlock the wallet
441
4
            if (!wallet->Unlock(passphrase)) {
442
0
                error = Untranslated("Error: Wallet was encrypted but could not be unlocked");
443
0
                status = DatabaseStatus::FAILED_ENCRYPT;
444
0
                return nullptr;
445
0
            }
446
447
            // Set a seed for the wallet
448
4
            {
449
4
                LOCK(wallet->cs_wallet);
450
4
                wallet->SetupDescriptorScriptPubKeyMans();
451
4
            }
452
453
            // Relock the wallet
454
4
            wallet->Lock();
455
4
        }
456
8
    }
457
458
582
    WITH_LOCK(wallet->cs_wallet, wallet->LogStats());
459
582
    NotifyWalletLoaded(context, wallet);
460
582
    AddWallet(context, wallet);
461
582
    wallet->postInitProcess();
462
463
    // Write the wallet settings
464
582
    UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
465
466
582
    status = DatabaseStatus::SUCCESS;
467
582
    return wallet;
468
582
}
469
470
// Re-creates wallet from the backup file by renaming and moving it into the wallet's directory.
471
// If 'load_after_restore=true', the wallet object will be fully initialized and appended to the context.
472
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, bool allow_unnamed)
473
45
{
474
    // Error if the wallet name is empty and allow_unnamed == false
475
    // allow_unnamed == true is only used by migration to migrate an unnamed wallet
476
45
    if (!allow_unnamed && wallet_name.empty()) {
477
1
        error = Untranslated("Wallet name cannot be empty");
478
1
        status = DatabaseStatus::FAILED_NEW_UNNAMED;
479
1
        return nullptr;
480
1
    }
481
482
44
    DatabaseOptions options;
483
44
    ReadDatabaseArgs(*context.args, options);
484
44
    options.require_existing = true;
485
486
44
    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::u8path(wallet_name));
487
44
    auto wallet_file = wallet_path / "wallet.dat";
488
44
    std::shared_ptr<CWallet> wallet;
489
44
    bool wallet_file_copied = false;
490
44
    bool created_parent_dir = false;
491
492
44
    try {
493
44
        if (!fs::exists(backup_file)) {
494
1
            error = Untranslated("Backup file does not exist");
495
1
            status = DatabaseStatus::FAILED_INVALID_BACKUP_FILE;
496
1
            return nullptr;
497
1
        }
498
499
        // Wallet directories are allowed to exist, but must not contain a .dat file.
500
        // Any existing wallet database is treated as a hard failure to prevent overwriting.
501
43
        if (fs::exists(wallet_path)) {
502
            // If this is a file, it is the db and we don't want to overwrite it.
503
13
            if (!fs::is_directory(wallet_path)) {
504
0
                error = Untranslated(strprintf("Failed to restore wallet. Database file exists '%s'.", fs::PathToString(wallet_path)));
505
0
                status = DatabaseStatus::FAILED_ALREADY_EXISTS;
506
0
                return nullptr;
507
0
            }
508
509
            // Check we are not going to overwrite an existing db file
510
13
            if (fs::exists(wallet_file)) {
511
2
                error = Untranslated(strprintf("Failed to restore wallet. Database file exists in '%s'.", fs::PathToString(wallet_file)));
512
2
                status = DatabaseStatus::FAILED_ALREADY_EXISTS;
513
2
                return nullptr;
514
2
            }
515
30
        } else {
516
            // The directory doesn't exist, create it
517
30
            if (!TryCreateDirectories(wallet_path)) {
518
0
                error = Untranslated(strprintf("Failed to restore database path '%s'.", fs::PathToString(wallet_path)));
519
0
                status = DatabaseStatus::FAILED_ALREADY_EXISTS;
520
0
                return nullptr;
521
0
            }
522
30
            created_parent_dir = true;
523
30
        }
524
525
41
        fs::copy_file(backup_file, wallet_file, fs::copy_options::none);
526
41
        wallet_file_copied = true;
527
528
41
        if (load_after_restore) {
529
33
            wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
530
33
        }
531
41
    } catch (const std::exception& e) {
532
0
        assert(!wallet);
533
0
        if (!error.empty()) error += Untranslated("\n");
534
0
        error += Untranslated(strprintf("Unexpected exception: %s", e.what()));
535
0
    }
536
537
    // Remove created wallet path only when loading fails
538
41
    if (load_after_restore && !wallet) {
539
14
        if (wallet_file_copied) fs::remove(wallet_file);
540
        // Clean up the parent directory if we created it during restoration.
541
        // As we have created it, it must be empty after deleting the wallet file.
542
14
        if (created_parent_dir) {
543
14
            Assume(fs::is_empty(wallet_path));
544
14
            fs::remove(wallet_path);
545
14
        }
546
14
    }
547
548
41
    return wallet;
549
44
}
550
551
/** @defgroup mapWallet
552
 *
553
 * @{
554
 */
555
556
const CWalletTx* CWallet::GetWalletTx(const Txid& hash) const
557
84.6k
{
558
84.6k
    AssertLockHeld(cs_wallet);
559
84.6k
    const auto it = mapWallet.find(hash);
560
84.6k
    if (it == mapWallet.end())
561
386
        return nullptr;
562
84.3k
    return &(it->second);
563
84.6k
}
564
565
void CWallet::UpgradeDescriptorCache()
566
428
{
567
428
    if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) || IsLocked() || IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
568
419
        return;
569
419
    }
570
571
44
    for (ScriptPubKeyMan* spkm : GetAllScriptPubKeyMans()) {
572
44
        DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
573
44
        desc_spkm->UpgradeDescriptorCache();
574
44
    }
575
9
    SetWalletFlag(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
576
9
}
577
578
/* Given a wallet passphrase string and an unencrypted master key, determine the proper key
579
 * derivation parameters (should take at least 100ms) and encrypt the master key. */
580
static bool EncryptMasterKey(const SecureString& wallet_passphrase, const CKeyingMaterial& plain_master_key, CMasterKey& master_key)
581
26
{
582
26
    constexpr MillisecondsDouble target_time{100};
583
26
    CCrypter crypter;
584
585
    // Get the weighted average of iterations we can do in 100ms over 2 runs.
586
74
    for (int i = 0; i < 2; i++){
587
50
        auto start_time{NodeClock::now()};
588
50
        crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod);
589
50
        auto elapsed_time{NodeClock::now() - start_time};
590
591
50
        if (elapsed_time <= 0s) {
592
            // We are probably in a test with a mocked clock.
593
2
            master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
594
2
            break;
595
2
        }
596
597
        // target_iterations : elapsed_iterations :: target_time : elapsed_time
598
48
        unsigned int target_iterations = master_key.nDeriveIterations * target_time / elapsed_time;
599
        // Get the weighted average with previous runs.
600
48
        master_key.nDeriveIterations = (i * master_key.nDeriveIterations + target_iterations) / (i + 1);
601
48
    }
602
603
26
    if (master_key.nDeriveIterations < CMasterKey::DEFAULT_DERIVE_ITERATIONS) {
604
14
        master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
605
14
    }
606
607
26
    if (!crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod)) {
608
0
        return false;
609
0
    }
610
26
    if (!crypter.Encrypt(plain_master_key, master_key.vchCryptedKey)) {
611
0
        return false;
612
0
    }
613
614
26
    return true;
615
26
}
616
617
static bool DecryptMasterKey(const SecureString& wallet_passphrase, const CMasterKey& master_key, CKeyingMaterial& plain_master_key)
618
83
{
619
83
    CCrypter crypter;
620
83
    if (!crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod)) {
621
0
        return false;
622
0
    }
623
83
    if (!crypter.Decrypt(master_key.vchCryptedKey, plain_master_key)) {
624
9
        return false;
625
9
    }
626
627
74
    return true;
628
83
}
629
630
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
631
79
{
632
79
    CKeyingMaterial plain_master_key;
633
634
79
    {
635
79
        LOCK(cs_wallet);
636
79
        for (const auto& [_, master_key] : mapMasterKeys)
637
79
        {
638
79
            if (!DecryptMasterKey(strWalletPassphrase, master_key, plain_master_key)) {
639
7
                continue; // try another master key
640
7
            }
641
72
            if (Unlock(plain_master_key)) {
642
                // Now that we've unlocked, upgrade the descriptor cache
643
72
                UpgradeDescriptorCache();
644
72
                return true;
645
72
            }
646
72
        }
647
79
    }
648
7
    return false;
649
79
}
650
651
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
652
4
{
653
4
    bool fWasLocked = IsLocked();
654
655
4
    {
656
4
        LOCK2(m_relock_mutex, cs_wallet);
657
4
        Lock();
658
659
4
        CKeyingMaterial plain_master_key;
660
4
        for (auto& [master_key_id, master_key] : mapMasterKeys)
661
4
        {
662
4
            if (!DecryptMasterKey(strOldWalletPassphrase, master_key, plain_master_key)) {
663
2
                return false;
664
2
            }
665
2
            if (Unlock(plain_master_key))
666
2
            {
667
2
                if (!EncryptMasterKey(strNewWalletPassphrase, plain_master_key, master_key)) {
668
0
                    return false;
669
0
                }
670
2
                WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", master_key.nDeriveIterations);
671
672
2
                WalletBatch(GetDatabase()).WriteMasterKey(master_key_id, master_key);
673
2
                if (fWasLocked)
674
2
                    Lock();
675
2
                return true;
676
2
            }
677
2
        }
678
4
    }
679
680
0
    return false;
681
4
}
682
683
void CWallet::SetLastBlockProcessedInMem(int block_height, uint256 block_hash)
684
33.5k
{
685
33.5k
    AssertLockHeld(cs_wallet);
686
687
33.5k
    m_last_block_processed = block_hash;
688
33.5k
    m_last_block_processed_height = block_height;
689
33.5k
}
690
691
void CWallet::SetLastBlockProcessed(int block_height, uint256 block_hash)
692
1.58k
{
693
1.58k
    AssertLockHeld(cs_wallet);
694
695
1.58k
    SetLastBlockProcessedInMem(block_height, block_hash);
696
1.58k
    WriteBestBlock();
697
1.58k
}
698
699
std::set<Txid> CWallet::GetConflicts(const Txid& txid) const
700
3.40k
{
701
3.40k
    std::set<Txid> result;
702
3.40k
    AssertLockHeld(cs_wallet);
703
704
3.40k
    const auto it = mapWallet.find(txid);
705
3.40k
    if (it == mapWallet.end())
706
0
        return result;
707
3.40k
    const CWalletTx& wtx = it->second;
708
709
3.40k
    std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
710
711
3.40k
    for (const CTxIn& txin : wtx.tx->vin)
712
5.62k
    {
713
5.62k
        if (mapTxSpends.count(txin.prevout) <= 1)
714
5.30k
            continue;  // No conflict if zero or one spends
715
326
        range = mapTxSpends.equal_range(txin.prevout);
716
1.05k
        for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
717
726
            result.insert(_it->second);
718
326
    }
719
3.40k
    return result;
720
3.40k
}
721
722
bool CWallet::HasWalletSpend(const CTransactionRef& tx) const
723
225
{
724
225
    AssertLockHeld(cs_wallet);
725
225
    const Txid& txid = tx->GetHash();
726
803
    for (unsigned int i = 0; i < tx->vout.size(); ++i) {
727
581
        if (IsSpent(COutPoint(txid, i))) {
728
3
            return true;
729
3
        }
730
581
    }
731
222
    return false;
732
225
}
733
734
void CWallet::Close()
735
14
{
736
14
    GetDatabase().Close();
737
14
}
738
739
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
740
13.4k
{
741
    // We want all the wallet transactions in range to have the same metadata as
742
    // the oldest (smallest nOrderPos).
743
    // So: find smallest nOrderPos:
744
745
13.4k
    int nMinOrderPos = std::numeric_limits<int>::max();
746
13.4k
    const CWalletTx* copyFrom = nullptr;
747
30.9k
    for (TxSpends::iterator it = range.first; it != range.second; ++it) {
748
17.4k
        const CWalletTx* wtx = &mapWallet.at(it->second);
749
17.4k
        if (wtx->nOrderPos < nMinOrderPos) {
750
17.4k
            nMinOrderPos = wtx->nOrderPos;
751
17.4k
            copyFrom = wtx;
752
17.4k
        }
753
17.4k
    }
754
755
13.4k
    if (!copyFrom) {
756
0
        return;
757
0
    }
758
759
    // Now copy data from copyFrom to rest:
760
30.9k
    for (TxSpends::iterator it = range.first; it != range.second; ++it)
761
17.4k
    {
762
17.4k
        const Txid& hash = it->second;
763
17.4k
        CWalletTx* copyTo = &mapWallet.at(hash);
764
17.4k
        if (copyFrom == copyTo) continue;
765
17.4k
        assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
766
4.05k
        if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
767
3
        copyTo->mapValue = copyFrom->mapValue;
768
3
        copyTo->vOrderForm = copyFrom->vOrderForm;
769
        // nTimeReceived not copied on purpose
770
3
        copyTo->nTimeSmart = copyFrom->nTimeSmart;
771
        // nOrderPos not copied on purpose
772
        // cached members not copied on purpose
773
3
    }
774
13.4k
}
775
776
/**
777
 * Outpoint is spent if any non-conflicted transaction
778
 * spends it:
779
 */
780
bool CWallet::IsSpent(const COutPoint& outpoint) const
781
468k
{
782
468k
    std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
783
468k
    range = mapTxSpends.equal_range(outpoint);
784
785
469k
    for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
786
288k
        const Txid& txid = it->second;
787
288k
        const auto mit = mapWallet.find(txid);
788
288k
        if (mit != mapWallet.end()) {
789
288k
            const auto& wtx = mit->second;
790
288k
            if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted())
791
287k
                return true; // Spent
792
288k
        }
793
288k
    }
794
181k
    return false;
795
468k
}
796
797
CWallet::SpendType CWallet::HowSpent(const COutPoint& outpoint) const
798
82.8k
{
799
82.8k
    SpendType st{SpendType::UNSPENT};
800
801
82.8k
    std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
802
82.8k
    range = mapTxSpends.equal_range(outpoint);
803
804
84.6k
    for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
805
49.2k
        const Txid& txid = it->second;
806
49.2k
        const auto mit = mapWallet.find(txid);
807
49.2k
        if (mit != mapWallet.end()) {
808
49.2k
            const auto& wtx = mit->second;
809
49.2k
            if (wtx.isConfirmed()) return SpendType::CONFIRMED;
810
1.82k
            if (wtx.InMempool()) {
811
1.60k
                st = SpendType::MEMPOOL;
812
1.60k
            } else if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted()) {
813
157
                if (st == SpendType::UNSPENT) st = SpendType::NONMEMPOOL;
814
157
            }
815
1.82k
        }
816
49.2k
    }
817
35.4k
    return st;
818
82.8k
}
819
820
void CWallet::AddToSpends(const COutPoint& outpoint, const Txid& txid)
821
13.4k
{
822
13.4k
    mapTxSpends.insert(std::make_pair(outpoint, txid));
823
824
13.4k
    UnlockCoin(outpoint);
825
826
13.4k
    std::pair<TxSpends::iterator, TxSpends::iterator> range;
827
13.4k
    range = mapTxSpends.equal_range(outpoint);
828
13.4k
    SyncMetaData(range);
829
13.4k
}
830
831
832
void CWallet::AddToSpends(const CWalletTx& wtx)
833
25.4k
{
834
25.4k
    if (wtx.IsCoinBase()) // Coinbases don't spend anything!
835
18.7k
        return;
836
837
6.68k
    for (const CTxIn& txin : wtx.tx->vin)
838
13.4k
        AddToSpends(txin.prevout, wtx.GetHash());
839
6.68k
}
840
841
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
842
24
{
843
    // Only descriptor wallets can be encrypted
844
24
    Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
845
846
24
    if (HasEncryptionKeys())
847
0
        return false;
848
849
24
    CKeyingMaterial plain_master_key;
850
851
24
    plain_master_key.resize(WALLET_CRYPTO_KEY_SIZE);
852
24
    GetStrongRandBytes(plain_master_key);
853
854
24
    CMasterKey master_key;
855
856
24
    master_key.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
857
24
    GetStrongRandBytes(master_key.vchSalt);
858
859
24
    if (!EncryptMasterKey(strWalletPassphrase, plain_master_key, master_key)) {
860
0
        return false;
861
0
    }
862
24
    WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", master_key.nDeriveIterations);
863
864
24
    {
865
24
        LOCK2(m_relock_mutex, cs_wallet);
866
24
        mapMasterKeys[++nMasterKeyMaxID] = master_key;
867
24
        WalletBatch* encrypted_batch = new WalletBatch(GetDatabase());
868
24
        if (!encrypted_batch->TxnBegin()) {
869
0
            delete encrypted_batch;
870
0
            encrypted_batch = nullptr;
871
0
            return false;
872
0
        }
873
24
        encrypted_batch->WriteMasterKey(nMasterKeyMaxID, master_key);
874
875
103
        for (const auto& spk_man_pair : m_spk_managers) {
876
103
            auto spk_man = spk_man_pair.second.get();
877
103
            if (!spk_man->Encrypt(plain_master_key, encrypted_batch)) {
878
0
                encrypted_batch->TxnAbort();
879
0
                delete encrypted_batch;
880
0
                encrypted_batch = nullptr;
881
                // We now probably have half of our keys encrypted in memory, and half not...
882
                // die and let the user reload the unencrypted wallet.
883
0
                assert(false);
884
0
            }
885
103
        }
886
887
24
        if (!encrypted_batch->TxnCommit()) {
888
0
            delete encrypted_batch;
889
0
            encrypted_batch = nullptr;
890
            // We now have keys encrypted in memory, but not on disk...
891
            // die to avoid confusion and let the user reload the unencrypted wallet.
892
0
            assert(false);
893
0
        }
894
895
24
        delete encrypted_batch;
896
24
        encrypted_batch = nullptr;
897
898
24
        Lock();
899
24
        Unlock(strWalletPassphrase);
900
901
        // Make new descriptors with a new seed
902
24
        if (!IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)) {
903
12
            SetupDescriptorScriptPubKeyMans();
904
12
        }
905
24
        Lock();
906
907
        // Need to completely rewrite the wallet file; if we don't, the database might keep
908
        // bits of the unencrypted private key in slack space in the database file.
909
24
        GetDatabase().Rewrite();
910
24
    }
911
0
    NotifyStatusChanged(this);
912
913
24
    return true;
914
24
}
915
916
DBErrors CWallet::ReorderTransactions()
917
0
{
918
0
    LOCK(cs_wallet);
919
0
    WalletBatch batch(GetDatabase());
920
921
    // Old wallets didn't have any defined order for transactions
922
    // Probably a bad idea to change the output of this
923
924
    // First: get all CWalletTx into a sorted-by-time multimap.
925
0
    typedef std::multimap<int64_t, CWalletTx*> TxItems;
926
0
    TxItems txByTime;
927
928
0
    for (auto& entry : mapWallet)
929
0
    {
930
0
        CWalletTx* wtx = &entry.second;
931
0
        txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
932
0
    }
933
934
0
    nOrderPosNext = 0;
935
0
    std::vector<int64_t> nOrderPosOffsets;
936
0
    for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
937
0
    {
938
0
        CWalletTx *const pwtx = (*it).second;
939
0
        int64_t& nOrderPos = pwtx->nOrderPos;
940
941
0
        if (nOrderPos == -1)
942
0
        {
943
0
            nOrderPos = nOrderPosNext++;
944
0
            nOrderPosOffsets.push_back(nOrderPos);
945
946
0
            if (!batch.WriteTx(*pwtx))
947
0
                return DBErrors::LOAD_FAIL;
948
0
        }
949
0
        else
950
0
        {
951
0
            int64_t nOrderPosOff = 0;
952
0
            for (const int64_t& nOffsetStart : nOrderPosOffsets)
953
0
            {
954
0
                if (nOrderPos >= nOffsetStart)
955
0
                    ++nOrderPosOff;
956
0
            }
957
0
            nOrderPos += nOrderPosOff;
958
0
            nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
959
960
0
            if (!nOrderPosOff)
961
0
                continue;
962
963
            // Since we're changing the order, write it back
964
0
            if (!batch.WriteTx(*pwtx))
965
0
                return DBErrors::LOAD_FAIL;
966
0
        }
967
0
    }
968
0
    batch.WriteOrderPosNext(nOrderPosNext);
969
970
0
    return DBErrors::LOAD_OK;
971
0
}
972
973
int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
974
17.6k
{
975
17.6k
    AssertLockHeld(cs_wallet);
976
17.6k
    int64_t nRet = nOrderPosNext++;
977
17.6k
    if (batch) {
978
17.6k
        batch->WriteOrderPosNext(nOrderPosNext);
979
17.6k
    } else {
980
0
        WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
981
0
    }
982
17.6k
    return nRet;
983
17.6k
}
984
985
void CWallet::MarkDirty()
986
856
{
987
856
    {
988
856
        LOCK(cs_wallet);
989
856
        for (auto& [_, wtx] : mapWallet)
990
3.15k
            wtx.MarkDirty();
991
856
    }
992
856
}
993
994
bool CWallet::MarkReplaced(const Txid& originalHash, const Txid& newHash)
995
98
{
996
98
    LOCK(cs_wallet);
997
998
98
    auto mi = mapWallet.find(originalHash);
999
1000
    // There is a bug if MarkReplaced is not called on an existing wallet transaction.
1001
98
    assert(mi != mapWallet.end());
1002
1003
98
    CWalletTx& wtx = (*mi).second;
1004
1005
    // Ensure for now that we're not overwriting data
1006
98
    assert(!wtx.mapValue.contains("replaced_by_txid"));
1007
1008
98
    wtx.mapValue["replaced_by_txid"] = newHash.ToString();
1009
1010
    // Refresh mempool status without waiting for transactionRemovedFromMempool or transactionAddedToMempool
1011
98
    RefreshMempoolStatus(wtx, chain());
1012
1013
98
    WalletBatch batch(GetDatabase());
1014
1015
98
    bool success = true;
1016
98
    if (!batch.WriteTx(wtx)) {
1017
0
        WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
1018
0
        success = false;
1019
0
    }
1020
1021
98
    NotifyTransactionChanged(originalHash, CT_UPDATED);
1022
1023
98
    return success;
1024
98
}
1025
1026
void CWallet::SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
1027
2.02k
{
1028
2.02k
    AssertLockHeld(cs_wallet);
1029
2.02k
    const CWalletTx* srctx = GetWalletTx(hash);
1030
2.02k
    if (!srctx) return;
1031
1032
1.88k
    CTxDestination dst;
1033
1.88k
    if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
1034
1.88k
        if (IsMine(dst)) {
1035
1.20k
            if (used != IsAddressPreviouslySpent(dst)) {
1036
19
                if (used) {
1037
19
                    tx_destinations.insert(dst);
1038
19
                }
1039
19
                SetAddressPreviouslySpent(batch, dst, used);
1040
19
            }
1041
1.20k
        }
1042
1.88k
    }
1043
1.88k
}
1044
1045
bool CWallet::IsSpentKey(const CScript& scriptPubKey) const
1046
439
{
1047
439
    AssertLockHeld(cs_wallet);
1048
439
    CTxDestination dest;
1049
439
    if (!ExtractDestination(scriptPubKey, dest)) {
1050
0
        return false;
1051
0
    }
1052
439
    if (IsAddressPreviouslySpent(dest)) {
1053
6
        return true;
1054
6
    }
1055
433
    return false;
1056
439
}
1057
1058
CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx, bool rescanning_old_block)
1059
25.1k
{
1060
25.1k
    LOCK(cs_wallet);
1061
1062
25.1k
    WalletBatch batch(GetDatabase());
1063
1064
25.1k
    Txid hash = tx->GetHash();
1065
1066
25.1k
    if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
1067
        // Mark used destinations
1068
864
        std::set<CTxDestination> tx_destinations;
1069
1070
2.02k
        for (const CTxIn& txin : tx->vin) {
1071
2.02k
            const COutPoint& op = txin.prevout;
1072
2.02k
            SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
1073
2.02k
        }
1074
1075
864
        MarkDestinationsDirty(tx_destinations);
1076
864
    }
1077
1078
    // Inserts only if not already there, returns tx inserted or tx found
1079
25.1k
    auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(tx, state));
1080
25.1k
    CWalletTx& wtx = (*ret.first).second;
1081
25.1k
    bool fInsertedNew = ret.second;
1082
25.1k
    bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
1083
25.1k
    if (fInsertedNew) {
1084
17.6k
        wtx.nTimeReceived = GetTime();
1085
17.6k
        wtx.nOrderPos = IncOrderPosNext(&batch);
1086
17.6k
        wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1087
17.6k
        wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block);
1088
17.6k
        AddToSpends(wtx);
1089
1090
        // Update birth time when tx time is older than it.
1091
17.6k
        MaybeUpdateBirthTime(wtx.GetTxTime());
1092
17.6k
    }
1093
1094
25.1k
    if (!fInsertedNew)
1095
7.48k
    {
1096
7.48k
        if (state.index() != wtx.m_state.index()) {
1097
4.36k
            wtx.m_state = state;
1098
4.36k
            fUpdated = true;
1099
4.36k
        } else {
1100
3.12k
            assert(TxStateSerializedIndex(wtx.m_state) == TxStateSerializedIndex(state));
1101
3.12k
            assert(TxStateSerializedBlockHash(wtx.m_state) == TxStateSerializedBlockHash(state));
1102
3.12k
        }
1103
        // If we have a witness-stripped version of this transaction, and we
1104
        // see a new version with a witness, then we must be upgrading a pre-segwit
1105
        // wallet.  Store the new version of the transaction with the witness,
1106
        // as the stripped-version must be invalid.
1107
        // TODO: Store all versions of the transaction, instead of just one.
1108
7.48k
        if (tx->HasWitness() && !wtx.tx->HasWitness()) {
1109
0
            wtx.SetTx(tx);
1110
0
            fUpdated = true;
1111
0
        }
1112
7.48k
    }
1113
1114
    // Mark inactive coinbase transactions and their descendants as abandoned
1115
25.1k
    if (wtx.IsCoinBase() && wtx.isInactive()) {
1116
540
        std::vector<CWalletTx*> txs{&wtx};
1117
1118
540
        TxStateInactive inactive_state = TxStateInactive{/*abandoned=*/true};
1119
1120
1.08k
        while (!txs.empty()) {
1121
541
            CWalletTx* desc_tx = txs.back();
1122
541
            txs.pop_back();
1123
541
            desc_tx->m_state = inactive_state;
1124
            // Break caches since we have changed the state
1125
541
            desc_tx->MarkDirty();
1126
541
            batch.WriteTx(*desc_tx);
1127
541
            MarkInputsDirty(desc_tx->tx);
1128
1.62k
            for (unsigned int i = 0; i < desc_tx->tx->vout.size(); ++i) {
1129
1.08k
                COutPoint outpoint(desc_tx->GetHash(), i);
1130
1.08k
                std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(outpoint);
1131
1.08k
                for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
1132
1
                    const auto wit = mapWallet.find(it->second);
1133
1
                    if (wit != mapWallet.end()) {
1134
1
                        txs.push_back(&wit->second);
1135
1
                    }
1136
1
                }
1137
1.08k
            }
1138
541
        }
1139
540
    }
1140
1141
    //// debug print
1142
25.1k
    std::string status{"no-change"};
1143
25.1k
    if (fInsertedNew || fUpdated) {
1144
22.0k
        status = fInsertedNew ? (fUpdated ? "new, update" : "new") : "update";
1145
22.0k
    }
1146
25.1k
    WalletLogPrintf("AddToWallet %s %s %s", hash.ToString(), status, TxStateString(state));
1147
1148
    // Write to disk
1149
25.1k
    if (fInsertedNew || fUpdated)
1150
22.0k
        if (!batch.WriteTx(wtx))
1151
0
            return nullptr;
1152
1153
    // Break debit/credit balance caches:
1154
25.1k
    wtx.MarkDirty();
1155
1156
    // Cache the outputs that belong to the wallet
1157
25.1k
    RefreshTXOsFromTx(wtx);
1158
1159
    // Notify UI of new or updated transaction
1160
25.1k
    NotifyTransactionChanged(hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1161
1162
25.1k
#if HAVE_SYSTEM
1163
    // notify an external script when a wallet transaction comes in or is updated
1164
25.1k
    std::string strCmd = m_notify_tx_changed_script;
1165
1166
25.1k
    if (!strCmd.empty())
1167
26
    {
1168
26
        ReplaceAll(strCmd, "%s", hash.GetHex());
1169
26
        if (auto* conf = wtx.state<TxStateConfirmed>())
1170
22
        {
1171
22
            ReplaceAll(strCmd, "%b", conf->confirmed_block_hash.GetHex());
1172
22
            ReplaceAll(strCmd, "%h", ToString(conf->confirmed_block_height));
1173
22
        } else {
1174
4
            ReplaceAll(strCmd, "%b", "unconfirmed");
1175
4
            ReplaceAll(strCmd, "%h", "-1");
1176
4
        }
1177
26
#ifndef WIN32
1178
        // Substituting the wallet name isn't currently supported on windows
1179
        // because windows shell escaping has not been implemented yet:
1180
        // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
1181
        // A few ways it could be implemented in the future are described in:
1182
        // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
1183
26
        ReplaceAll(strCmd, "%w", ShellEscape(GetName()));
1184
26
#endif
1185
26
        std::thread t(runCommand, strCmd);
1186
26
        t.detach(); // thread runs free
1187
26
    }
1188
25.1k
#endif
1189
1190
25.1k
    return &wtx;
1191
25.1k
}
1192
1193
bool CWallet::LoadToWallet(const Txid& hash, const UpdateWalletTxFn& fill_wtx)
1194
7.76k
{
1195
7.76k
    const auto& ins = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(nullptr, TxStateInactive{}));
1196
7.76k
    CWalletTx& wtx = ins.first->second;
1197
7.76k
    if (!fill_wtx(wtx, ins.second)) {
1198
0
        return false;
1199
0
    }
1200
    // If wallet doesn't have a chain (e.g when using bitcoin-wallet tool),
1201
    // don't bother to update txn.
1202
7.76k
    if (HaveChain()) {
1203
7.69k
      wtx.updateState(chain());
1204
7.69k
    }
1205
7.76k
    if (/* insertion took place */ ins.second) {
1206
7.76k
        wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1207
7.76k
    }
1208
7.76k
    AddToSpends(wtx);
1209
7.94k
    for (const CTxIn& txin : wtx.tx->vin) {
1210
7.94k
        auto it = mapWallet.find(txin.prevout.hash);
1211
7.94k
        if (it != mapWallet.end()) {
1212
489
            CWalletTx& prevtx = it->second;
1213
489
            if (auto* prev = prevtx.state<TxStateBlockConflicted>()) {
1214
3
                MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, wtx.GetHash());
1215
3
            }
1216
489
        }
1217
7.94k
    }
1218
1219
    // Update birth time when tx time is older than it.
1220
7.76k
    MaybeUpdateBirthTime(wtx.GetTxTime());
1221
1222
    // Make sure the tx outputs are known by the wallet
1223
7.76k
    RefreshTXOsFromTx(wtx);
1224
7.76k
    return true;
1225
7.76k
}
1226
1227
bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block)
1228
142k
{
1229
142k
    const CTransaction& tx = *ptx;
1230
142k
    {
1231
142k
        AssertLockHeld(cs_wallet);
1232
1233
142k
        if (auto* conf = std::get_if<TxStateConfirmed>(&state)) {
1234
172k
            for (const CTxIn& txin : tx.vin) {
1235
172k
                std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1236
180k
                while (range.first != range.second) {
1237
8.04k
                    if (range.first->second != tx.GetHash()) {
1238
204
                        WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), conf->confirmed_block_hash.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1239
204
                        MarkConflicted(conf->confirmed_block_hash, conf->confirmed_block_height, range.first->second);
1240
204
                    }
1241
8.04k
                    range.first++;
1242
8.04k
                }
1243
172k
            }
1244
134k
        }
1245
1246
142k
        bool fExisted = mapWallet.contains(tx.GetHash());
1247
142k
        if (fExisted && !fUpdate) return false;
1248
142k
        if (fExisted || IsMine(tx) || IsFromMe(tx))
1249
23.6k
        {
1250
            /* Check if any keys in the wallet keypool that were supposed to be unused
1251
             * have appeared in a new transaction. If so, remove those keys from the keypool.
1252
             * This can happen when restoring an old wallet backup that does not contain
1253
             * the mostly recently created transactions from newer versions of the wallet.
1254
             */
1255
1256
            // loop though all outputs
1257
109k
            for (const CTxOut& txout: tx.vout) {
1258
109k
                for (const auto& spk_man : GetScriptPubKeyMans(txout.scriptPubKey)) {
1259
49.0k
                    for (auto &dest : spk_man->MarkUnusedAddresses(txout.scriptPubKey)) {
1260
                        // If internal flag is not defined try to infer it from the ScriptPubKeyMan
1261
24.4k
                        if (!dest.internal.has_value()) {
1262
24.4k
                            dest.internal = IsInternalScriptPubKeyMan(spk_man);
1263
24.4k
                        }
1264
1265
                        // skip if can't determine whether it's a receiving address or not
1266
24.4k
                        if (!dest.internal.has_value()) continue;
1267
1268
                        // If this is a receiving address and it's not in the address book yet
1269
                        // (e.g. it wasn't generated on this node or we're restoring from backup)
1270
                        // add it to the address book for proper transaction accounting
1271
16.2k
                        if (!*dest.internal && !FindAddressBookEntry(dest.dest, /* allow_change= */ false)) {
1272
10.1k
                            SetAddressBook(dest.dest, "", AddressPurpose::RECEIVE);
1273
10.1k
                        }
1274
16.2k
                    }
1275
49.0k
                }
1276
109k
            }
1277
1278
            // Block disconnection override an abandoned tx as unconfirmed
1279
            // which means user may have to call abandontransaction again
1280
23.6k
            TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
wallet.cpp:_ZZN6wallet7CWallet24AddToWalletIfInvolvingMeERKSt10shared_ptrIK12CTransactionERKSt7variantIJNS_16TxStateConfirmedENS_16TxStateInMempoolENS_15TxStateInactiveEEEbbENK3$_0clIRKS8_EES7_IJS8_S9_NS_22TxStateBlockConflictedESA_NS_19TxStateUnrecognizedEEEOT_
Line
Count
Source
1280
19.2k
            TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
wallet.cpp:_ZZN6wallet7CWallet24AddToWalletIfInvolvingMeERKSt10shared_ptrIK12CTransactionERKSt7variantIJNS_16TxStateConfirmedENS_16TxStateInMempoolENS_15TxStateInactiveEEEbbENK3$_0clIRKS9_EES7_IJS8_S9_NS_22TxStateBlockConflictedESA_NS_19TxStateUnrecognizedEEEOT_
Line
Count
Source
1280
3.79k
            TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
wallet.cpp:_ZZN6wallet7CWallet24AddToWalletIfInvolvingMeERKSt10shared_ptrIK12CTransactionERKSt7variantIJNS_16TxStateConfirmedENS_16TxStateInMempoolENS_15TxStateInactiveEEEbbENK3$_0clIRKSA_EES7_IJS8_S9_NS_22TxStateBlockConflictedESA_NS_19TxStateUnrecognizedEEEOT_
Line
Count
Source
1280
588
            TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
1281
23.6k
            CWalletTx* wtx = AddToWallet(MakeTransactionRef(tx), tx_state, /*update_wtx=*/nullptr, rescanning_old_block);
1282
23.6k
            if (!wtx) {
1283
                // Can only be nullptr if there was a db write error (missing db, read-only db or a db engine internal writing error).
1284
                // As we only store arriving transaction in this process, and we don't want an inconsistent state, let's throw an error.
1285
0
                throw std::runtime_error("DB error adding transaction to wallet, write failed");
1286
0
            }
1287
23.6k
            return true;
1288
23.6k
        }
1289
142k
    }
1290
118k
    return false;
1291
142k
}
1292
1293
bool CWallet::TransactionCanBeAbandoned(const Txid& hashTx) const
1294
0
{
1295
0
    LOCK(cs_wallet);
1296
0
    const CWalletTx* wtx = GetWalletTx(hashTx);
1297
0
    return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 && !wtx->InMempool();
1298
0
}
1299
1300
void CWallet::UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1301
62
{
1302
    // Find all other txs in our wallet that spend utxos from this parent
1303
    // so that we can mark them as mempool-conflicted by this new tx.
1304
242
    for (long unsigned int i = 0; i < parent_wtx.tx->vout.size(); i++) {
1305
225
        for (auto range = mapTxSpends.equal_range(COutPoint(parent_wtx.tx->GetHash(), i)); range.first != range.second; range.first++) {
1306
45
            const Txid& sibling_txid = range.first->second;
1307
            // Skip the child_tx itself
1308
45
            if (sibling_txid == child_txid) continue;
1309
17
            RecursiveUpdateTxState(/*batch=*/nullptr, sibling_txid, [&child_txid, add_conflict](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1310
17
                return add_conflict ? (wtx.mempool_conflicts.insert(child_txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED)
1311
17
                                    : (wtx.mempool_conflicts.erase(child_txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED);
1312
17
            });
1313
17
        }
1314
180
    }
1315
62
}
1316
1317
void CWallet::MarkInputsDirty(const CTransactionRef& tx)
1318
32.5k
{
1319
43.3k
    for (const CTxIn& txin : tx->vin) {
1320
43.3k
        auto it = mapWallet.find(txin.prevout.hash);
1321
43.3k
        if (it != mapWallet.end()) {
1322
24.9k
            it->second.MarkDirty();
1323
24.9k
        }
1324
43.3k
    }
1325
32.5k
}
1326
1327
bool CWallet::AbandonTransaction(const Txid& hashTx)
1328
9
{
1329
9
    LOCK(cs_wallet);
1330
9
    auto it = mapWallet.find(hashTx);
1331
9
    assert(it != mapWallet.end());
1332
9
    return AbandonTransaction(it->second);
1333
9
}
1334
1335
bool CWallet::AbandonTransaction(CWalletTx& tx)
1336
441
{
1337
    // Can't mark abandoned if confirmed or in mempool
1338
441
    if (GetTxDepthInMainChain(tx) != 0 || tx.InMempool()) {
1339
3
        return false;
1340
3
    }
1341
1342
460
    auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1343
        // If the orig tx was not in block/mempool, none of its spends can be.
1344
460
        assert(!wtx.isConfirmed());
1345
460
        assert(!wtx.InMempool());
1346
        // If already conflicted or abandoned, no need to set abandoned
1347
460
        if (!wtx.isBlockConflicted() && !wtx.isAbandoned()) {
1348
351
            wtx.m_state = TxStateInactive{/*abandoned=*/true};
1349
351
            return TxUpdate::NOTIFY_CHANGED;
1350
351
        }
1351
109
        return TxUpdate::UNCHANGED;
1352
460
    };
1353
1354
    // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1355
    // States are not permanent, so these transactions can become unabandoned if they are re-added to the
1356
    // mempool, or confirmed in a block, or conflicted.
1357
    // Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1358
    // states change will remain abandoned and will require manual broadcast if the user wants them.
1359
1360
438
    RecursiveUpdateTxState(tx.GetHash(), try_updating_state);
1361
1362
438
    return true;
1363
441
}
1364
1365
void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx)
1366
207
{
1367
207
    LOCK(cs_wallet);
1368
1369
    // If number of conflict confirms cannot be determined, this means
1370
    // that the block is still unknown or not yet part of the main chain,
1371
    // for example when loading the wallet during a reindex. Do nothing in that
1372
    // case.
1373
207
    if (m_last_block_processed_height < 0 || conflicting_height < 0) {
1374
3
        return;
1375
3
    }
1376
204
    int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1377
204
    if (conflictconfirms >= 0)
1378
0
        return;
1379
1380
213
    auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1381
213
        if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
1382
            // Block is 'more conflicted' than current confirm; update.
1383
            // Mark transaction as conflicted with this block.
1384
199
            wtx.m_state = TxStateBlockConflicted{hashBlock, conflicting_height};
1385
199
            return TxUpdate::CHANGED;
1386
199
        }
1387
14
        return TxUpdate::UNCHANGED;
1388
213
    };
1389
1390
    // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
1391
204
    RecursiveUpdateTxState(hashTx, try_updating_state);
1392
1393
204
}
1394
1395
650
void CWallet::RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
1396
650
    WalletBatch batch(GetDatabase());
1397
650
    RecursiveUpdateTxState(&batch, tx_hash, try_updating_state);
1398
650
}
1399
1400
19.7k
void CWallet::RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
1401
19.7k
    std::set<Txid> todo;
1402
19.7k
    std::set<Txid> done;
1403
1404
19.7k
    todo.insert(tx_hash);
1405
1406
39.5k
    while (!todo.empty()) {
1407
19.8k
        Txid now = *todo.begin();
1408
19.8k
        todo.erase(now);
1409
19.8k
        done.insert(now);
1410
19.8k
        auto it = mapWallet.find(now);
1411
19.8k
        assert(it != mapWallet.end());
1412
19.8k
        CWalletTx& wtx = it->second;
1413
1414
19.8k
        TxUpdate update_state = try_updating_state(wtx);
1415
19.8k
        if (update_state != TxUpdate::UNCHANGED) {
1416
8.39k
            wtx.MarkDirty();
1417
8.39k
            if (batch) batch->WriteTx(wtx);
1418
            // Iterate over all its outputs, and update those tx states as well (if applicable)
1419
25.2k
            for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
1420
16.8k
                std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
1421
16.8k
                for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
1422
52
                    if (!done.contains(iter->second)) {
1423
52
                        todo.insert(iter->second);
1424
52
                    }
1425
52
                }
1426
16.8k
            }
1427
1428
8.39k
            if (update_state == TxUpdate::NOTIFY_CHANGED) {
1429
351
                NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1430
351
            }
1431
1432
            // If a transaction changes its tx state, that usually changes the balance
1433
            // available of the outputs it spends. So force those to be recomputed
1434
8.39k
            MarkInputsDirty(wtx.tx);
1435
8.39k
        }
1436
19.8k
    }
1437
19.7k
}
1438
1439
bool CWallet::SyncTransaction(const CTransactionRef& ptx, const SyncTxState& state, bool update_tx, bool rescanning_old_block)
1440
142k
{
1441
142k
    if (!AddToWalletIfInvolvingMe(ptx, state, update_tx, rescanning_old_block))
1442
118k
        return false; // Not one of ours
1443
1444
    // If a transaction changes 'conflicted' state, that changes the balance
1445
    // available of the outputs it spends. So force those to be
1446
    // recomputed, also:
1447
23.6k
    MarkInputsDirty(ptx);
1448
23.6k
    return true;
1449
142k
}
1450
1451
7.48k
void CWallet::transactionAddedToMempool(const CTransactionRef& tx) {
1452
7.48k
    LOCK(cs_wallet);
1453
7.48k
    SyncTransaction(tx, TxStateInMempool{});
1454
1455
7.48k
    auto it = mapWallet.find(tx->GetHash());
1456
7.48k
    if (it != mapWallet.end()) {
1457
3.79k
        RefreshMempoolStatus(it->second, chain());
1458
3.79k
    }
1459
1460
7.48k
    const Txid& txid = tx->GetHash();
1461
1462
14.2k
    for (const CTxIn& tx_in : tx->vin) {
1463
        // For each wallet transaction spending this prevout..
1464
26.6k
        for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
1465
12.4k
            const Txid& spent_id = range.first->second;
1466
            // Skip the recently added tx
1467
12.4k
            if (spent_id == txid) continue;
1468
3.93k
            RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1469
3.93k
                return wtx.mempool_conflicts.insert(txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
1470
3.93k
            });
1471
3.92k
        }
1472
1473
14.2k
    }
1474
1475
7.48k
    if (tx->version == TRUC_VERSION) {
1476
        // Unconfirmed TRUC transactions are only allowed a 1-parent-1-child topology.
1477
        // For any unconfirmed v3 parents (there should be a maximum of 1 except in reorgs),
1478
        // record this child so the wallet doesn't try to spend any other outputs
1479
402
        for (const CTxIn& tx_in : tx->vin) {
1480
402
            auto parent_it = mapWallet.find(tx_in.prevout.hash);
1481
402
            if (parent_it != mapWallet.end()) {
1482
164
                CWalletTx& parent_wtx = parent_it->second;
1483
164
                if (parent_wtx.isUnconfirmed()) {
1484
31
                    parent_wtx.truc_child_in_mempool = tx->GetHash();
1485
                    // Even though these siblings do not spend the same utxos, they can't
1486
                    // be present in the mempool at the same time because of TRUC policy rules
1487
31
                    UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/true);
1488
31
                }
1489
164
            }
1490
402
        }
1491
162
    }
1492
7.48k
}
1493
1494
39.6k
void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {
1495
39.6k
    LOCK(cs_wallet);
1496
39.6k
    auto it = mapWallet.find(tx->GetHash());
1497
39.6k
    if (it != mapWallet.end()) {
1498
13.4k
        RefreshMempoolStatus(it->second, chain());
1499
13.4k
    }
1500
    // Handle transactions that were removed from the mempool because they
1501
    // conflict with transactions in a newly connected block.
1502
39.6k
    if (reason == MemPoolRemovalReason::CONFLICT) {
1503
        // Trigger external -walletnotify notifications for these transactions.
1504
        // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
1505
        //
1506
        // 1. The transactionRemovedFromMempool callback does not currently
1507
        //    provide the conflicting block's hash and height, and for backwards
1508
        //    compatibility reasons it may not be not safe to store conflicted
1509
        //    wallet transactions with a null block hash. See
1510
        //    https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1511
        // 2. For most of these transactions, the wallet's internal conflict
1512
        //    detection in the blockConnected handler will subsequently call
1513
        //    MarkConflicted and update them with CONFLICTED status anyway. This
1514
        //    applies to any wallet transaction that has inputs spent in the
1515
        //    block, or that has ancestors in the wallet with inputs spent by
1516
        //    the block.
1517
        // 3. Longstanding behavior since the sync implementation in
1518
        //    https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1519
        //    implementation before that was to mark these transactions
1520
        //    unconfirmed rather than conflicted.
1521
        //
1522
        // Nothing described above should be seen as an unchangeable requirement
1523
        // when improving this code in the future. The wallet's heuristics for
1524
        // distinguishing between conflicted and unconfirmed transactions are
1525
        // imperfect, and could be improved in general, see
1526
        // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1527
19
        SyncTransaction(tx, TxStateInactive{});
1528
19
    }
1529
1530
39.6k
    const Txid& txid = tx->GetHash();
1531
1532
47.3k
    for (const CTxIn& tx_in : tx->vin) {
1533
        // Iterate over all wallet transactions spending txin.prev
1534
        // and recursively mark them as no longer conflicting with
1535
        // txid
1536
62.5k
        for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
1537
15.1k
            const Txid& spent_id = range.first->second;
1538
1539
15.1k
            RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1540
15.1k
                return wtx.mempool_conflicts.erase(txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
1541
15.1k
            });
1542
15.1k
        }
1543
47.3k
    }
1544
1545
39.6k
    if (tx->version == TRUC_VERSION) {
1546
        // If this tx has a parent, unset its truc_child_in_mempool to make it possible
1547
        // to spend from the parent again. If this tx was replaced by another
1548
        // child of the same parent, transactionAddedToMempool
1549
        // will update truc_child_in_mempool
1550
836
        for (const CTxIn& tx_in : tx->vin) {
1551
836
            auto parent_it = mapWallet.find(tx_in.prevout.hash);
1552
836
            if (parent_it != mapWallet.end()) {
1553
598
                CWalletTx& parent_wtx = parent_it->second;
1554
598
                if (parent_wtx.truc_child_in_mempool == tx->GetHash()) {
1555
31
                    parent_wtx.truc_child_in_mempool = std::nullopt;
1556
31
                    UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/false);
1557
31
                }
1558
598
            }
1559
836
        }
1560
374
    }
1561
39.6k
}
1562
1563
void CWallet::blockConnected(const ChainstateRole& role, const interfaces::BlockInfo& block)
1564
31.1k
{
1565
31.1k
    if (role.historical) {
1566
100
        return;
1567
100
    }
1568
31.1k
    assert(block.data);
1569
31.0k
    LOCK(cs_wallet);
1570
1571
    // Update the best block in memory first. This will set the best block's height, which is
1572
    // needed by MarkConflicted.
1573
31.0k
    SetLastBlockProcessedInMem(block.height, block.hash);
1574
1575
    // No need to scan block if it was created before the wallet birthday.
1576
    // Uses chain max time and twice the grace period to adjust time for block time variability.
1577
31.0k
    if (block.chain_time_max < m_birth_time.load() - (TIMESTAMP_WINDOW * 2)) return;
1578
1579
    // Scan block
1580
30.6k
    bool wallet_updated = false;
1581
69.9k
    for (size_t index = 0; index < block.data->vtx.size(); index++) {
1582
39.3k
        wallet_updated |= SyncTransaction(block.data->vtx[index], TxStateConfirmed{block.hash, block.height, static_cast<int>(index)});
1583
39.3k
        transactionRemovedFromMempool(block.data->vtx[index], MemPoolRemovalReason::BLOCK);
1584
39.3k
    }
1585
1586
    // Update on disk if this block resulted in us updating a tx, or periodically every 144 blocks (~1 day)
1587
30.6k
    if (wallet_updated || block.height % 144 == 0) {
1588
11.0k
        WriteBestBlock();
1589
11.0k
    }
1590
30.6k
}
1591
1592
void CWallet::blockDisconnected(const interfaces::BlockInfo& block)
1593
932
{
1594
932
    assert(block.data);
1595
932
    LOCK(cs_wallet);
1596
1597
    // At block disconnection, this will change an abandoned transaction to
1598
    // be unconfirmed, whether or not the transaction is added back to the mempool.
1599
    // User may have to call abandontransaction again. It may be addressed in the
1600
    // future with a stickier abandoned state or even removing abandontransaction call.
1601
932
    int disconnect_height = block.height;
1602
1603
1.92k
    for (size_t index = 0; index < block.data->vtx.size(); index++) {
1604
988
        const CTransactionRef& ptx = block.data->vtx[index];
1605
        // Coinbase transactions are not only inactive but also abandoned,
1606
        // meaning they should never be relayed standalone via the p2p protocol.
1607
988
        SyncTransaction(ptx, TxStateInactive{/*abandoned=*/index == 0});
1608
1609
1.09k
        for (const CTxIn& tx_in : ptx->vin) {
1610
            // No other wallet transactions conflicted with this transaction
1611
1.09k
            if (!mapTxSpends.contains(tx_in.prevout)) continue;
1612
1613
89
            std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
1614
1615
            // For all of the spends that conflict with this transaction
1616
186
            for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
1617
97
                CWalletTx& wtx = mapWallet.find(_it->second)->second;
1618
1619
97
                if (!wtx.isBlockConflicted()) continue;
1620
1621
12
                auto try_updating_state = [&](CWalletTx& tx) {
1622
12
                    if (!tx.isBlockConflicted()) return TxUpdate::UNCHANGED;
1623
12
                    if (tx.state<TxStateBlockConflicted>()->conflicting_block_height >= disconnect_height) {
1624
11
                        tx.m_state = TxStateInactive{};
1625
11
                        return TxUpdate::CHANGED;
1626
11
                    }
1627
1
                    return TxUpdate::UNCHANGED;
1628
12
                };
1629
1630
8
                RecursiveUpdateTxState(wtx.tx->GetHash(), try_updating_state);
1631
8
            }
1632
89
        }
1633
988
    }
1634
1635
    // Update the best block
1636
932
    SetLastBlockProcessed(block.height - 1, *Assert(block.prev_hash));
1637
932
}
1638
1639
void CWallet::updatedBlockTip()
1640
30.7k
{
1641
30.7k
    m_best_block_time = GetTime();
1642
30.7k
}
1643
1644
6.53k
void CWallet::BlockUntilSyncedToCurrentChain() const {
1645
6.53k
    AssertLockNotHeld(cs_wallet);
1646
    // Skip the queue-draining stuff if we know we're caught up with
1647
    // chain().Tip(), otherwise put a callback in the validation interface queue and wait
1648
    // for the queue to drain enough to execute it (indicating we are caught up
1649
    // at least with the time we entered this function).
1650
6.53k
    uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1651
6.53k
    chain().waitForNotificationsIfTipChanged(last_block_hash);
1652
6.53k
}
1653
1654
// Note that this function doesn't distinguish between a 0-valued input,
1655
// and a not-"is mine" input.
1656
CAmount CWallet::GetDebit(const CTxIn &txin) const
1657
2.45k
{
1658
2.45k
    LOCK(cs_wallet);
1659
2.45k
    auto txo = GetTXO(txin.prevout);
1660
2.45k
    if (txo) {
1661
1.54k
        return txo->GetTxOut().nValue;
1662
1.54k
    }
1663
901
    return 0;
1664
2.45k
}
1665
1666
bool CWallet::IsMine(const CTxOut& txout) const
1667
574k
{
1668
574k
    AssertLockHeld(cs_wallet);
1669
574k
    return IsMine(txout.scriptPubKey);
1670
574k
}
1671
1672
bool CWallet::IsMine(const CTxDestination& dest) const
1673
31.8k
{
1674
31.8k
    AssertLockHeld(cs_wallet);
1675
31.8k
    return IsMine(GetScriptForDestination(dest));
1676
31.8k
}
1677
1678
bool CWallet::IsMine(const CScript& script) const
1679
609k
{
1680
609k
    AssertLockHeld(cs_wallet);
1681
1682
    // Search the cache so that IsMine is called only on the relevant SPKMs instead of on everything in m_spk_managers
1683
609k
    const auto& it = m_cached_spks.find(script);
1684
609k
    if (it != m_cached_spks.end()) {
1685
195k
        bool res = false;
1686
195k
        for (const auto& spkm : it->second) {
1687
195k
            res = res || spkm->IsMine(script);
1688
195k
        }
1689
195k
        Assume(res);
1690
195k
        return res;
1691
195k
    }
1692
1693
414k
    return false;
1694
609k
}
1695
1696
bool CWallet::IsMine(const CTransaction& tx) const
1697
135k
{
1698
135k
    AssertLockHeld(cs_wallet);
1699
135k
    for (const CTxOut& txout : tx.vout)
1700
337k
        if (IsMine(txout))
1701
15.9k
            return true;
1702
119k
    return false;
1703
135k
}
1704
1705
bool CWallet::IsMine(const COutPoint& outpoint) const
1706
2.97k
{
1707
2.97k
    AssertLockHeld(cs_wallet);
1708
2.97k
    auto wtx = GetWalletTx(outpoint.hash);
1709
2.97k
    if (!wtx) {
1710
22
        return false;
1711
22
    }
1712
2.95k
    if (outpoint.n >= wtx->tx->vout.size()) {
1713
0
        return false;
1714
0
    }
1715
2.95k
    return IsMine(wtx->tx->vout[outpoint.n]);
1716
2.95k
}
1717
1718
bool CWallet::IsFromMe(const CTransaction& tx) const
1719
129k
{
1720
129k
    LOCK(cs_wallet);
1721
168k
    for (const CTxIn& txin : tx.vin) {
1722
168k
        if (GetTXO(txin.prevout)) return true;
1723
168k
    }
1724
126k
    return false;
1725
129k
}
1726
1727
CAmount CWallet::GetDebit(const CTransaction& tx) const
1728
1.35k
{
1729
1.35k
    CAmount nDebit = 0;
1730
1.35k
    for (const CTxIn& txin : tx.vin)
1731
2.43k
    {
1732
2.43k
        nDebit += GetDebit(txin);
1733
2.43k
        if (!MoneyRange(nDebit))
1734
0
            throw std::runtime_error(std::string(__func__) + ": value out of range");
1735
2.43k
    }
1736
1.35k
    return nDebit;
1737
1.35k
}
1738
1739
bool CWallet::IsHDEnabled() const
1740
4
{
1741
    // All Active ScriptPubKeyMans must be HD for this to be true
1742
4
    bool result = false;
1743
32
    for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
1744
32
        if (!spk_man->IsHDEnabled()) return false;
1745
32
        result = true;
1746
32
    }
1747
4
    return result;
1748
4
}
1749
1750
bool CWallet::CanGetAddresses(bool internal) const
1751
11.3k
{
1752
11.3k
    LOCK(cs_wallet);
1753
11.3k
    if (m_spk_managers.empty()) return false;
1754
12.2k
    for (OutputType t : OUTPUT_TYPES) {
1755
12.2k
        auto spk_man = GetScriptPubKeyMan(t, internal);
1756
12.2k
        if (spk_man && spk_man->CanGetAddresses(internal)) {
1757
11.3k
            return true;
1758
11.3k
        }
1759
12.2k
    }
1760
13
    return false;
1761
11.3k
}
1762
1763
void CWallet::SetWalletFlag(uint64_t flags)
1764
69
{
1765
69
    WalletBatch batch(GetDatabase());
1766
69
    return SetWalletFlagWithDB(batch, flags);
1767
69
}
1768
1769
void CWallet::SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags)
1770
103
{
1771
103
    LOCK(cs_wallet);
1772
103
    m_wallet_flags |= flags;
1773
103
    if (!batch.WriteWalletFlags(m_wallet_flags))
1774
0
        throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1775
103
}
1776
1777
void CWallet::UnsetWalletFlag(uint64_t flag)
1778
1
{
1779
1
    WalletBatch batch(GetDatabase());
1780
1
    UnsetWalletFlagWithDB(batch, flag);
1781
1
}
1782
1783
void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
1784
3.65k
{
1785
3.65k
    LOCK(cs_wallet);
1786
3.65k
    m_wallet_flags &= ~flag;
1787
3.65k
    if (!batch.WriteWalletFlags(m_wallet_flags))
1788
0
        throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1789
3.65k
}
1790
1791
void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
1792
3.65k
{
1793
3.65k
    UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
1794
3.65k
}
1795
1796
bool CWallet::IsWalletFlagSet(uint64_t flag) const
1797
204k
{
1798
204k
    return (m_wallet_flags & flag);
1799
204k
}
1800
1801
bool CWallet::LoadWalletFlags(uint64_t flags)
1802
958
{
1803
958
    LOCK(cs_wallet);
1804
958
    if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1805
        // contains unknown non-tolerable wallet flags
1806
0
        return false;
1807
0
    }
1808
958
    m_wallet_flags = flags;
1809
1810
958
    return true;
1811
958
}
1812
1813
void CWallet::InitWalletFlags(uint64_t flags)
1814
604
{
1815
604
    LOCK(cs_wallet);
1816
1817
    // We should never be writing unknown non-tolerable wallet flags
1818
604
    assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1819
    // This should only be used once, when creating a new wallet - so current flags are expected to be blank
1820
604
    assert(m_wallet_flags == 0);
1821
1822
604
    if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
1823
0
        throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1824
0
    }
1825
1826
604
    if (!LoadWalletFlags(flags)) assert(false);
1827
604
}
1828
1829
uint64_t CWallet::GetWalletFlags() const
1830
433
{
1831
433
    return m_wallet_flags;
1832
433
}
1833
1834
void CWallet::MaybeUpdateBirthTime(int64_t time)
1835
32.6k
{
1836
32.6k
    int64_t birthtime = m_birth_time.load();
1837
32.6k
    if (time < birthtime) {
1838
1.38k
        m_birth_time = time;
1839
1.38k
    }
1840
32.6k
}
1841
1842
/**
1843
 * Scan active chain for relevant transactions after importing keys. This should
1844
 * be called whenever new keys are added to the wallet, with the oldest key
1845
 * creation time.
1846
 *
1847
 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1848
 * returned will be higher than startTime if relevant blocks could not be read.
1849
 */
1850
int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1851
613
{
1852
    // Find starting block. May be null if nCreateTime is greater than the
1853
    // highest blockchain timestamp, in which case there is nothing that needs
1854
    // to be scanned.
1855
613
    int start_height = 0;
1856
613
    uint256 start_block;
1857
613
    bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
1858
613
    WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
1859
1860
613
    if (start) {
1861
        // TODO: this should take into account failure by ScanResult::USER_ABORT
1862
613
        ScanResult result = ScanForWalletTransactions(start_block, start_height, /*max_height=*/{}, reserver, /*fUpdate=*/update, /*save_progress=*/false);
1863
613
        if (result.status == ScanResult::FAILURE) {
1864
1
            int64_t time_max;
1865
1
            CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
1866
1
            return time_max + TIMESTAMP_WINDOW + 1;
1867
1
        }
1868
613
    }
1869
612
    return startTime;
1870
613
}
1871
1872
/**
1873
 * Scan the block chain (starting in start_block) for transactions
1874
 * from or to us. If fUpdate is true, found transactions that already
1875
 * exist in the wallet will be updated. If max_height is not set, the
1876
 * mempool will be scanned as well.
1877
 *
1878
 * @param[in] start_block Scan starting block. If block is not on the active
1879
 *                        chain, the scan will return SUCCESS immediately.
1880
 * @param[in] start_height Height of start_block
1881
 * @param[in] max_height  Optional max scanning height. If unset there is
1882
 *                        no maximum and scanning can continue to the tip
1883
 *
1884
 * @return ScanResult returning scan information and indicating success or
1885
 *         failure. Return status will be set to SUCCESS if scan was
1886
 *         successful. FAILURE if a complete rescan was not possible (due to
1887
 *         pruning or corruption). USER_ABORT if the rescan was aborted before
1888
 *         it could complete.
1889
 *
1890
 * @pre Caller needs to make sure start_block (and the optional stop_block) are on
1891
 * the main chain after to the addition of any new keys you want to detect
1892
 * transactions for.
1893
 */
1894
CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress)
1895
689
{
1896
689
    constexpr auto INTERVAL_TIME{60s};
1897
689
    auto current_time{reserver.now()};
1898
689
    auto start_time{reserver.now()};
1899
1900
689
    assert(reserver.isReserved());
1901
1902
689
    uint256 block_hash = start_block;
1903
689
    ScanResult result;
1904
1905
689
    std::unique_ptr<FastWalletRescanFilter> fast_rescan_filter;
1906
689
    if (chain().hasBlockFilterIndex(BlockFilterType::BASIC)) fast_rescan_filter = std::make_unique<FastWalletRescanFilter>(*this);
1907
1908
689
    WalletLogPrintf("Rescan started from block %s... (%s)\n", start_block.ToString(),
1909
689
                    fast_rescan_filter ? "fast variant using block filters" : "slow variant inspecting all blocks");
1910
1911
689
    fAbortRescan = false;
1912
689
    ShowProgress(strprintf("[%s] %s", DisplayName(), _("Rescanning…")), 0); // show rescan progress in GUI as dialog or on splashscreen, if rescan required on startup (e.g. due to corruption)
1913
689
    uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1914
689
    uint256 end_hash = tip_hash;
1915
689
    if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
1916
689
    double progress_begin = chain().guessVerificationProgress(block_hash);
1917
689
    double progress_end = chain().guessVerificationProgress(end_hash);
1918
689
    double progress_current = progress_begin;
1919
689
    int block_height = start_height;
1920
74.2k
    while (!fAbortRescan && !chain().shutdownRequested()) {
1921
74.2k
        if (progress_end - progress_begin > 0.0) {
1922
74.0k
            m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
1923
74.0k
        } else { // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
1924
212
            m_scanning_progress = 0;
1925
212
        }
1926
74.2k
        if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1927
818
            ShowProgress(strprintf("[%s] %s", DisplayName(), _("Rescanning…")), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1928
818
        }
1929
1930
74.2k
        bool next_interval = reserver.now() >= current_time + INTERVAL_TIME;
1931
74.2k
        if (next_interval) {
1932
2
            current_time = reserver.now();
1933
2
            WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
1934
2
        }
1935
1936
74.2k
        bool fetch_block{true};
1937
74.2k
        if (fast_rescan_filter) {
1938
615
            fast_rescan_filter->UpdateIfNeeded();
1939
615
            auto matches_block{fast_rescan_filter->MatchesBlock(block_hash)};
1940
615
            if (matches_block.has_value()) {
1941
615
                if (*matches_block) {
1942
65
                    LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block_height, block_hash.ToString());
1943
550
                } else {
1944
550
                    result.last_scanned_block = block_hash;
1945
550
                    result.last_scanned_height = block_height;
1946
550
                    fetch_block = false;
1947
550
                }
1948
615
            } else {
1949
0
                LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (WARNING: block filter not found!)\n", block_height, block_hash.ToString());
1950
0
            }
1951
615
        }
1952
1953
        // Find next block separately from reading data above, because reading
1954
        // is slow and there might be a reorg while it is read.
1955
74.2k
        bool block_still_active = false;
1956
74.2k
        bool next_block = false;
1957
74.2k
        uint256 next_block_hash;
1958
74.2k
        chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
1959
1960
74.2k
        if (fetch_block) {
1961
            // Read block data and locator if needed (the locator is usually null unless we need to save progress)
1962
73.7k
            CBlock block;
1963
73.7k
            CBlockLocator loc;
1964
            // Find block
1965
73.7k
            FoundBlock found_block{FoundBlock().data(block)};
1966
73.7k
            if (save_progress && next_interval) found_block.locator(loc);
1967
73.7k
            chain().findBlock(block_hash, found_block);
1968
1969
73.7k
            if (!block.IsNull()) {
1970
73.6k
                LOCK(cs_wallet);
1971
73.6k
                if (!block_still_active) {
1972
                    // Abort scan if current block is no longer active, to prevent
1973
                    // marking transactions as coming from the wrong block.
1974
0
                    result.last_failed_block = block_hash;
1975
0
                    result.status = ScanResult::FAILURE;
1976
0
                    break;
1977
0
                }
1978
168k
                for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1979
94.6k
                    SyncTransaction(block.vtx[posInBlock], TxStateConfirmed{block_hash, block_height, static_cast<int>(posInBlock)}, fUpdate, /*rescanning_old_block=*/true);
1980
94.6k
                }
1981
                // scan succeeded, record block as most recent successfully scanned
1982
73.6k
                result.last_scanned_block = block_hash;
1983
73.6k
                result.last_scanned_height = block_height;
1984
1985
73.6k
                if (!loc.IsNull()) {
1986
2
                    WalletLogPrintf("Saving scan progress %d.\n", block_height);
1987
2
                    WalletBatch batch(GetDatabase());
1988
2
                    batch.WriteBestBlock(loc);
1989
2
                }
1990
73.6k
            } else {
1991
                // could not scan block, keep scanning but record this block as the most recent failure
1992
104
                result.last_failed_block = block_hash;
1993
104
                result.status = ScanResult::FAILURE;
1994
104
            }
1995
73.7k
        }
1996
74.2k
        if (max_height && block_height >= *max_height) {
1997
2
            break;
1998
2
        }
1999
        // If rescanning was triggered with cs_wallet permanently locked (AttachChain), additional blocks that were connected during the rescan
2000
        // aren't processed here but will be processed with the pending blockConnected notifications after the lock is released.
2001
        // If rescanning without a permanent cs_wallet lock, additional blocks that were added during the rescan will be re-processed if
2002
        // the notification was processed and the last block height was updated.
2003
74.2k
        if (block_height >= WITH_LOCK(cs_wallet, return GetLastBlockHeight())) {
2004
686
            break;
2005
686
        }
2006
2007
73.5k
        {
2008
73.5k
            if (!next_block) {
2009
                // break successfully when rescan has reached the tip, or
2010
                // previous block is no longer on the chain due to a reorg
2011
1
                break;
2012
1
            }
2013
2014
            // increment block and verification progress
2015
73.5k
            block_hash = next_block_hash;
2016
73.5k
            ++block_height;
2017
73.5k
            progress_current = chain().guessVerificationProgress(block_hash);
2018
2019
            // handle updated tip hash
2020
73.5k
            const uint256 prev_tip_hash = tip_hash;
2021
73.5k
            tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
2022
73.5k
            if (!max_height && prev_tip_hash != tip_hash) {
2023
                // in case the tip has changed, update progress max
2024
0
                progress_end = chain().guessVerificationProgress(tip_hash);
2025
0
            }
2026
73.5k
        }
2027
73.5k
    }
2028
689
    if (!max_height) {
2029
687
        WalletLogPrintf("Scanning current mempool transactions.\n");
2030
687
        WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
2031
687
    }
2032
689
    ShowProgress(strprintf("[%s] %s", DisplayName(), _("Rescanning…")), 100); // hide progress dialog in GUI
2033
689
    if (block_height && fAbortRescan) {
2034
0
        WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
2035
0
        result.status = ScanResult::USER_ABORT;
2036
689
    } else if (block_height && chain().shutdownRequested()) {
2037
0
        WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
2038
0
        result.status = ScanResult::USER_ABORT;
2039
689
    } else {
2040
689
        WalletLogPrintf("Rescan completed in %15dms\n", Ticks<std::chrono::milliseconds>(reserver.now() - start_time));
2041
689
    }
2042
689
    return result;
2043
689
}
2044
2045
bool CWallet::SubmitTxMemoryPoolAndRelay(CWalletTx& wtx,
2046
                                         std::string& err_string,
2047
                                         node::TxBroadcast broadcast_method) const
2048
1.66k
{
2049
1.66k
    AssertLockHeld(cs_wallet);
2050
2051
    // Can't relay if wallet is not broadcasting
2052
1.66k
    if (!GetBroadcastTransactions()) return false;
2053
    // Don't relay abandoned transactions
2054
1.66k
    if (wtx.isAbandoned()) return false;
2055
    // Don't try to submit coinbase transactions. These would fail anyway but would
2056
    // cause log spam.
2057
1.66k
    if (wtx.IsCoinBase()) return false;
2058
    // Don't try to submit conflicted or confirmed transactions.
2059
1.66k
    if (GetTxDepthInMainChain(wtx) != 0) return false;
2060
2061
1.66k
    const char* what{""};
2062
1.66k
    switch (broadcast_method) {
2063
1.53k
    case node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL:
2064
1.53k
        what = "to mempool and for broadcast to peers";
2065
1.53k
        break;
2066
131
    case node::TxBroadcast::MEMPOOL_NO_BROADCAST:
2067
131
        what = "to mempool without broadcast";
2068
131
        break;
2069
0
    case node::TxBroadcast::NO_MEMPOOL_PRIVATE_BROADCAST:
2070
0
        what = "for private broadcast without adding to the mempool";
2071
0
        break;
2072
1.66k
    }
2073
1.66k
    WalletLogPrintf("Submitting wtx %s %s\n", wtx.GetHash().ToString(), what);
2074
    // We must set TxStateInMempool here. Even though it will also be set later by the
2075
    // entered-mempool callback, if we did not there would be a race where a
2076
    // user could call sendmoney in a loop and hit spurious out of funds errors
2077
    // because we think that this newly generated transaction's change is
2078
    // unavailable as we're not yet aware that it is in the mempool.
2079
    //
2080
    // If broadcast fails for any reason, trying to set wtx.m_state here would be incorrect.
2081
    // If transaction was previously in the mempool, it should be updated when
2082
    // TransactionRemovedFromMempool fires.
2083
1.66k
    bool ret = chain().broadcastTransaction(wtx.tx, m_default_max_tx_fee, broadcast_method, err_string);
2084
1.66k
    if (ret) wtx.m_state = TxStateInMempool{};
2085
1.66k
    return ret;
2086
1.66k
}
2087
2088
std::set<Txid> CWallet::GetTxConflicts(const CWalletTx& wtx) const
2089
3.40k
{
2090
3.40k
    AssertLockHeld(cs_wallet);
2091
2092
3.40k
    const Txid myHash{wtx.GetHash()};
2093
3.40k
    std::set<Txid> result{GetConflicts(myHash)};
2094
3.40k
    result.erase(myHash);
2095
3.40k
    return result;
2096
3.40k
}
2097
2098
bool CWallet::ShouldResend() const
2099
84
{
2100
    // Don't attempt to resubmit if the wallet is configured to not broadcast
2101
84
    if (!fBroadcastTransactions) return false;
2102
2103
    // During reindex, importing and IBD, old wallet transactions become
2104
    // unconfirmed. Don't resend them as that would spam other nodes.
2105
    // We only allow forcing mempool submission when not relaying to avoid this spam.
2106
84
    if (!chain().isReadyToBroadcast()) return false;
2107
2108
    // Do this infrequently and randomly to avoid giving away
2109
    // that these are our transactions.
2110
31
    if (NodeClock::now() < m_next_resend) return false;
2111
2112
4
    return true;
2113
31
}
2114
2115
1.04k
NodeClock::time_point CWallet::GetDefaultNextResend() { return FastRandomContext{}.rand_uniform_delay(NodeClock::now() + 12h, 24h); }
2116
2117
// Resubmit transactions from the wallet to the mempool, optionally asking the
2118
// mempool to relay them. On startup, we will do this for all unconfirmed
2119
// transactions but will not ask the mempool to relay them. We do this on startup
2120
// to ensure that our own mempool is aware of our transactions. There
2121
// is a privacy side effect here as not broadcasting on startup also means that we won't
2122
// inform the world of our wallet's state, particularly if the wallet (or node) is not
2123
// yet synced.
2124
//
2125
// Otherwise this function is called periodically in order to relay our unconfirmed txs.
2126
// We do this on a random timer to slightly obfuscate which transactions
2127
// come from our wallet.
2128
//
2129
// TODO: Ideally, we'd only resend transactions that we think should have been
2130
// mined in the most recent block. Any transaction that wasn't in the top
2131
// blockweight of transactions in the mempool shouldn't have been mined,
2132
// and so is probably just sitting in the mempool waiting to be confirmed.
2133
// Rebroadcasting does nothing to speed up confirmation and only damages
2134
// privacy.
2135
//
2136
// The `force` option results in all unconfirmed transactions being submitted to
2137
// the mempool. This does not necessarily result in those transactions being relayed,
2138
// that depends on the `broadcast_method` option. Periodic rebroadcast uses the pattern
2139
// broadcast_method=TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL force=false, while loading into
2140
// the mempool (on start, or after import) uses
2141
// broadcast_method=TxBroadcast::MEMPOOL_NO_BROADCAST force=true.
2142
void CWallet::ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force)
2143
1.49k
{
2144
    // Don't attempt to resubmit if the wallet is configured to not broadcast,
2145
    // even if forcing.
2146
1.49k
    if (!fBroadcastTransactions) return;
2147
2148
1.49k
    int submitted_tx_count = 0;
2149
2150
1.49k
    { // cs_wallet scope
2151
1.49k
        LOCK(cs_wallet);
2152
2153
        // First filter for the transactions we want to rebroadcast.
2154
        // We use a set with WalletTxOrderComparator so that rebroadcasting occurs in insertion order
2155
1.49k
        std::set<CWalletTx*, WalletTxOrderComparator> to_submit;
2156
13.4k
        for (auto& [txid, wtx] : mapWallet) {
2157
            // Only rebroadcast unconfirmed txs
2158
13.4k
            if (!wtx.isUnconfirmed()) continue;
2159
2160
            // Attempt to rebroadcast all txes more than 5 minutes older than
2161
            // the last block, or all txs if forcing.
2162
138
            if (!force && wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
2163
137
            to_submit.insert(&wtx);
2164
137
        }
2165
        // Now try submitting the transactions to the memory pool and (optionally) relay them.
2166
1.49k
        for (auto wtx : to_submit) {
2167
137
            std::string unused_err_string;
2168
137
            if (SubmitTxMemoryPoolAndRelay(*wtx, unused_err_string, broadcast_method)) ++submitted_tx_count;
2169
137
        }
2170
1.49k
    } // cs_wallet
2171
2172
1.49k
    if (submitted_tx_count > 0) {
2173
56
        WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
2174
56
    }
2175
1.49k
}
2176
2177
/** @} */ // end of mapWallet
2178
2179
void MaybeResendWalletTxs(WalletContext& context)
2180
31
{
2181
84
    for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
2182
84
        if (!pwallet->ShouldResend()) continue;
2183
4
        pwallet->ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*force=*/false);
2184
4
        pwallet->SetNextResend();
2185
4
    }
2186
31
}
2187
2188
2189
bool CWallet::SignTransaction(CMutableTransaction& tx) const
2190
2.57k
{
2191
2.57k
    AssertLockHeld(cs_wallet);
2192
2193
    // Build coins map
2194
2.57k
    std::map<COutPoint, Coin> coins;
2195
8.93k
    for (auto& input : tx.vin) {
2196
8.93k
        const auto mi = mapWallet.find(input.prevout.hash);
2197
8.93k
        if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2198
0
            return false;
2199
0
        }
2200
8.93k
        const CWalletTx& wtx = mi->second;
2201
8.93k
        int prev_height = wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height : 0;
2202
8.93k
        coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], prev_height, wtx.IsCoinBase());
2203
8.93k
    }
2204
2.57k
    std::map<int, bilingual_str> input_errors;
2205
2.57k
    return SignTransaction(tx, coins, SIGHASH_DEFAULT, input_errors);
2206
2.57k
}
2207
2208
bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2209
2.90k
{
2210
    // Try to sign with all ScriptPubKeyMans
2211
17.7k
    for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2212
        // spk_man->SignTransaction will return true if the transaction is complete,
2213
        // so we can exit early and return true if that happens
2214
17.7k
        if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2215
2.89k
            return true;
2216
2.89k
        }
2217
17.7k
    }
2218
2219
    // At this point, one input was not fully signed otherwise we would have exited already
2220
10
    return false;
2221
2.90k
}
2222
2223
std::optional<PSBTError> CWallet::FillPSBT(PartiallySignedTransaction& psbtx, const common::PSBTFillOptions& options, bool& complete, size_t* n_signed) const
2224
1.15k
{
2225
1.15k
    if (n_signed) {
2226
0
        *n_signed = 0;
2227
0
    }
2228
1.15k
    LOCK(cs_wallet);
2229
    // Get all of the previous transactions
2230
4.83k
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2231
3.68k
        const CTxIn& txin = psbtx.tx->vin[i];
2232
3.68k
        PSBTInput& input = psbtx.inputs.at(i);
2233
2234
3.68k
        if (PSBTInputSigned(input)) {
2235
18
            continue;
2236
18
        }
2237
2238
        // If we have no utxo, grab it from the wallet.
2239
3.66k
        if (!input.non_witness_utxo) {
2240
2.24k
            const Txid& txhash = txin.prevout.hash;
2241
2.24k
            const auto it = mapWallet.find(txhash);
2242
2.24k
            if (it != mapWallet.end()) {
2243
1.93k
                const CWalletTx& wtx = it->second;
2244
                // We only need the non_witness_utxo, which is a superset of the witness_utxo.
2245
                //   The signing code will switch to the smaller witness_utxo if this is ok.
2246
1.93k
                input.non_witness_utxo = wtx.tx;
2247
1.93k
            }
2248
2.24k
        }
2249
3.66k
    }
2250
2251
1.15k
    const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
2252
2253
    // Fill in information from ScriptPubKeyMans
2254
8.20k
    for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2255
8.20k
        int n_signed_this_spkm = 0;
2256
8.20k
        const auto error{spk_man->FillPSBT(psbtx, txdata, options, &n_signed_this_spkm)};
2257
8.20k
        if (error) {
2258
9
            return error;
2259
9
        }
2260
2261
8.19k
        if (n_signed) {
2262
0
            (*n_signed) += n_signed_this_spkm;
2263
0
        }
2264
8.19k
    }
2265
2266
1.14k
    RemoveUnnecessaryTransactions(psbtx);
2267
2268
    // Complete if every input is now signed
2269
1.14k
    complete = true;
2270
4.81k
    for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
2271
3.67k
        complete &= PSBTInputSignedAndVerified(psbtx, i, &txdata);
2272
3.67k
    }
2273
2274
1.14k
    return {};
2275
1.15k
}
2276
2277
SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2278
9
{
2279
9
    SignatureData sigdata;
2280
9
    CScript script_pub_key = GetScriptForDestination(pkhash);
2281
28
    for (const auto& spk_man_pair : m_spk_managers) {
2282
28
        if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2283
9
            LOCK(cs_wallet);  // DescriptorScriptPubKeyMan calls IsLocked which can lock cs_wallet in a deadlocking order
2284
9
            return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2285
9
        }
2286
28
    }
2287
0
    return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2288
9
}
2289
2290
OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
2291
3.63k
{
2292
    // If -changetype is specified, always use that change type.
2293
3.63k
    if (change_type) {
2294
343
        return *change_type;
2295
343
    }
2296
2297
    // if m_default_address_type is legacy, use legacy address as change.
2298
3.29k
    if (m_default_address_type == OutputType::LEGACY) {
2299
26
        return OutputType::LEGACY;
2300
26
    }
2301
2302
3.26k
    bool any_tr{false};
2303
3.26k
    bool any_wpkh{false};
2304
3.26k
    bool any_sh{false};
2305
3.26k
    bool any_pkh{false};
2306
2307
38.9k
    for (const auto& recipient : vecSend) {
2308
38.9k
        if (std::get_if<WitnessV1Taproot>(&recipient.dest)) {
2309
327
            any_tr = true;
2310
38.6k
        } else if (std::get_if<WitnessV0KeyHash>(&recipient.dest)) {
2311
31.5k
            any_wpkh = true;
2312
31.5k
        } else if (std::get_if<ScriptHash>(&recipient.dest)) {
2313
1.06k
            any_sh = true;
2314
6.05k
        } else if (std::get_if<PKHash>(&recipient.dest)) {
2315
5.93k
            any_pkh = true;
2316
5.93k
        }
2317
38.9k
    }
2318
2319
3.26k
    const bool has_bech32m_spkman(GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/true));
2320
3.26k
    if (has_bech32m_spkman && any_tr) {
2321
        // Currently tr is the only type supported by the BECH32M spkman
2322
323
        return OutputType::BECH32M;
2323
323
    }
2324
2.94k
    const bool has_bech32_spkman(GetScriptPubKeyMan(OutputType::BECH32, /*internal=*/true));
2325
2.94k
    if (has_bech32_spkman && any_wpkh) {
2326
        // Currently wpkh is the only type supported by the BECH32 spkman
2327
2.58k
        return OutputType::BECH32;
2328
2.58k
    }
2329
355
    const bool has_p2sh_segwit_spkman(GetScriptPubKeyMan(OutputType::P2SH_SEGWIT, /*internal=*/true));
2330
355
    if (has_p2sh_segwit_spkman && any_sh) {
2331
        // Currently sh_wpkh is the only type supported by the P2SH_SEGWIT spkman
2332
        // As of 2021 about 80% of all SH are wrapping WPKH, so use that
2333
49
        return OutputType::P2SH_SEGWIT;
2334
49
    }
2335
306
    const bool has_legacy_spkman(GetScriptPubKeyMan(OutputType::LEGACY, /*internal=*/true));
2336
306
    if (has_legacy_spkman && any_pkh) {
2337
        // Currently pkh is the only type supported by the LEGACY spkman
2338
41
        return OutputType::LEGACY;
2339
41
    }
2340
2341
265
    if (has_bech32m_spkman) {
2342
233
        return OutputType::BECH32M;
2343
233
    }
2344
32
    if (has_bech32_spkman) {
2345
14
        return OutputType::BECH32;
2346
14
    }
2347
    // else use m_default_address_type for change
2348
18
    return m_default_address_type;
2349
32
}
2350
2351
void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
2352
1.53k
{
2353
1.53k
    LOCK(cs_wallet);
2354
1.53k
    WalletLogPrintf("CommitTransaction:\n%s\n", util::RemoveSuffixView(tx->ToString(), "\n"));
2355
2356
    // Add tx to wallet, because if it has change it's also ours,
2357
    // otherwise just for transaction history.
2358
1.53k
    CWalletTx* wtx = AddToWallet(tx, TxStateInactive{}, [&](CWalletTx& wtx, bool new_tx) {
2359
1.53k
        CHECK_NONFATAL(wtx.mapValue.empty());
2360
1.53k
        CHECK_NONFATAL(wtx.vOrderForm.empty());
2361
1.53k
        wtx.mapValue = std::move(mapValue);
2362
1.53k
        wtx.vOrderForm = std::move(orderForm);
2363
1.53k
        return true;
2364
1.53k
    });
2365
2366
    // wtx can only be null if the db write failed.
2367
1.53k
    if (!wtx) {
2368
0
        throw std::runtime_error(std::string(__func__) + ": Wallet db error, transaction commit failed");
2369
0
    }
2370
2371
    // Notify that old coins are spent
2372
3.93k
    for (const CTxIn& txin : tx->vin) {
2373
3.93k
        CWalletTx &coin = mapWallet.at(txin.prevout.hash);
2374
3.93k
        coin.MarkDirty();
2375
3.93k
        NotifyTransactionChanged(coin.GetHash(), CT_UPDATED);
2376
3.93k
    }
2377
2378
1.53k
    if (!fBroadcastTransactions) {
2379
        // Don't submit tx to the mempool
2380
7
        return;
2381
7
    }
2382
2383
1.52k
    std::string err_string;
2384
1.52k
    if (!SubmitTxMemoryPoolAndRelay(*wtx, err_string, node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL)) {
2385
4
        WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
2386
        // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2387
4
    }
2388
1.52k
}
2389
2390
DBErrors CWallet::PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings)
2391
360
{
2392
360
    LOCK(cs_wallet);
2393
2394
360
    Assert(m_spk_managers.empty());
2395
360
    Assert(m_wallet_flags == 0);
2396
360
    DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
2397
2398
360
    if (m_spk_managers.empty()) {
2399
22
        assert(m_external_spk_managers.empty());
2400
22
        assert(m_internal_spk_managers.empty());
2401
22
    }
2402
2403
360
    const auto wallet_file = m_database->Filename();
2404
360
    switch (nLoadWalletRet) {
2405
356
    case DBErrors::LOAD_OK:
2406
356
        break;
2407
1
    case DBErrors::NONCRITICAL_ERROR:
2408
1
        warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
2409
1
                                       " or address metadata may be missing or incorrect."),
2410
1
            wallet_file));
2411
1
        break;
2412
0
    case DBErrors::NEED_RESCAN:
2413
0
        warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
2414
0
                                       " Rescanning wallet."), wallet_file));
2415
0
        break;
2416
1
    case DBErrors::CORRUPT:
2417
1
        error = strprintf(_("Error loading %s: Wallet corrupted"), wallet_file);
2418
1
        break;
2419
0
    case DBErrors::TOO_NEW:
2420
0
        error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), wallet_file, CLIENT_NAME);
2421
0
        break;
2422
0
    case DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED:
2423
0
        error = strprintf(_("Error loading %s: External signer wallet being loaded without external signer support compiled"), wallet_file);
2424
0
        break;
2425
1
    case DBErrors::UNKNOWN_DESCRIPTOR:
2426
1
        error = strprintf(_("Unrecognized descriptor found. Loading wallet %s\n\n"
2427
1
                            "The wallet might have been created on a newer version.\n"
2428
1
                            "Please try running the latest software version.\n"), wallet_file);
2429
1
        break;
2430
1
    case DBErrors::UNEXPECTED_LEGACY_ENTRY:
2431
1
        error = strprintf(_("Unexpected legacy entry in descriptor wallet found. Loading wallet %s\n\n"
2432
1
                            "The wallet might have been tampered with or created with malicious intent.\n"), wallet_file);
2433
1
        break;
2434
0
    case DBErrors::LEGACY_WALLET:
2435
0
        error = strprintf(_("Error loading %s: Wallet is a legacy wallet. Please migrate to a descriptor wallet using the migration tool (migratewallet RPC)."), wallet_file);
2436
0
        break;
2437
0
    case DBErrors::LOAD_FAIL:
2438
0
        error = strprintf(_("Error loading %s"), wallet_file);
2439
0
        break;
2440
360
    } // no default case, so the compiler can warn about missing cases
2441
360
    return nLoadWalletRet;
2442
360
}
2443
2444
util::Result<void> CWallet::RemoveTxs(std::vector<Txid>& txs_to_remove)
2445
7
{
2446
7
    AssertLockHeld(cs_wallet);
2447
7
    bilingual_str str_err;  // future: make RunWithinTxn return a util::Result
2448
7
    bool was_txn_committed = RunWithinTxn(GetDatabase(), /*process_desc=*/"remove transactions", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
2449
7
        util::Result<void> result{RemoveTxs(batch, txs_to_remove)};
2450
7
        if (!result) str_err = util::ErrorString(result);
2451
7
        return result.has_value();
2452
7
    });
2453
7
    if (!str_err.empty()) return util::Error{str_err};
2454
6
    if (!was_txn_committed) return util::Error{_("Error starting/committing db txn for wallet transactions removal process")};
2455
6
    return {}; // all good
2456
6
}
2457
2458
util::Result<void> CWallet::RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove)
2459
13
{
2460
13
    AssertLockHeld(cs_wallet);
2461
13
    if (!batch.HasActiveTxn()) return util::Error{strprintf(_("The transactions removal process can only be executed within a db txn"))};
2462
2463
    // Check for transaction existence and remove entries from disk
2464
13
    std::vector<decltype(mapWallet)::const_iterator> erased_txs;
2465
13
    bilingual_str str_err;
2466
18
    for (const Txid& hash : txs_to_remove) {
2467
18
        auto it_wtx = mapWallet.find(hash);
2468
18
        if (it_wtx == mapWallet.end()) {
2469
1
            return util::Error{strprintf(_("Transaction %s does not belong to this wallet"), hash.GetHex())};
2470
1
        }
2471
17
        if (!batch.EraseTx(hash)) {
2472
0
            return util::Error{strprintf(_("Failure removing transaction: %s"), hash.GetHex())};
2473
0
        }
2474
17
        erased_txs.emplace_back(it_wtx);
2475
17
    }
2476
2477
    // Register callback to update the memory state only when the db txn is actually dumped to disk
2478
12
    batch.RegisterTxnListener({.on_commit=[&, erased_txs]() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
2479
        // Update the in-memory state and notify upper layers about the removals
2480
17
        for (const auto& it : erased_txs) {
2481
17
            const Txid hash{it->first};
2482
17
            wtxOrdered.erase(it->second.m_it_wtxOrdered);
2483
17
            for (const auto& txin : it->second.tx->vin) {
2484
17
                auto range = mapTxSpends.equal_range(txin.prevout);
2485
20
                for (auto iter = range.first; iter != range.second; ++iter) {
2486
20
                    if (iter->second == hash) {
2487
17
                        mapTxSpends.erase(iter);
2488
17
                        break;
2489
17
                    }
2490
20
                }
2491
17
            }
2492
46
            for (unsigned int i = 0; i < it->second.tx->vout.size(); ++i) {
2493
29
                m_txos.erase(COutPoint(hash, i));
2494
29
            }
2495
17
            mapWallet.erase(it);
2496
17
            NotifyTransactionChanged(hash, CT_DELETED);
2497
17
        }
2498
2499
12
        MarkDirty();
2500
12
    }, .on_abort={}});
2501
2502
12
    return {};
2503
13
}
2504
2505
bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
2506
28.0k
{
2507
28.0k
    bool fUpdated = false;
2508
28.0k
    bool is_mine;
2509
28.0k
    std::optional<AddressPurpose> purpose;
2510
28.0k
    {
2511
28.0k
        LOCK(cs_wallet);
2512
28.0k
        std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
2513
28.0k
        fUpdated = mi != m_address_book.end() && !mi->second.IsChange();
2514
2515
28.0k
        CAddressBookData& record = mi != m_address_book.end() ? mi->second : m_address_book[address];
2516
28.0k
        record.SetLabel(strName);
2517
28.0k
        is_mine = IsMine(address);
2518
28.0k
        if (new_purpose) { /* update purpose only if requested */
2519
28.0k
            record.purpose = new_purpose;
2520
28.0k
        }
2521
28.0k
        purpose = record.purpose;
2522
28.0k
    }
2523
2524
28.0k
    const std::string& encoded_dest = EncodeDestination(address);
2525
28.0k
    if (new_purpose && !batch.WritePurpose(encoded_dest, PurposeToString(*new_purpose))) {
2526
0
        WalletLogPrintf("Error: fail to write address book 'purpose' entry\n");
2527
0
        return false;
2528
0
    }
2529
28.0k
    if (!batch.WriteName(encoded_dest, strName)) {
2530
0
        WalletLogPrintf("Error: fail to write address book 'name' entry\n");
2531
0
        return false;
2532
0
    }
2533
2534
    // In very old wallets, address purpose may not be recorded so we derive it from IsMine
2535
28.0k
    NotifyAddressBookChanged(address, strName, is_mine,
2536
28.0k
                             purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND),
2537
28.0k
                             (fUpdated ? CT_UPDATED : CT_NEW));
2538
28.0k
    return true;
2539
28.0k
}
2540
2541
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose)
2542
28.0k
{
2543
28.0k
    WalletBatch batch(GetDatabase());
2544
28.0k
    return SetAddressBookWithDB(batch, address, strName, purpose);
2545
28.0k
}
2546
2547
bool CWallet::DelAddressBook(const CTxDestination& address)
2548
0
{
2549
0
    return RunWithinTxn(GetDatabase(), /*process_desc=*/"address book entry removal", [&](WalletBatch& batch){
2550
0
        return DelAddressBookWithDB(batch, address);
2551
0
    });
2552
0
}
2553
2554
bool CWallet::DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address)
2555
27
{
2556
27
    const std::string& dest = EncodeDestination(address);
2557
27
    {
2558
27
        LOCK(cs_wallet);
2559
        // If we want to delete receiving addresses, we should avoid calling EraseAddressData because it will delete the previously_spent value. Could instead just erase the label so it becomes a change address, and keep the data.
2560
        // NOTE: This isn't a problem for sending addresses because they don't have any data that needs to be kept.
2561
        // When adding new address data, it should be considered here whether to retain or delete it.
2562
27
        if (IsMine(address)) {
2563
0
            WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, CLIENT_BUGREPORT);
2564
0
            return false;
2565
0
        }
2566
        // Delete data rows associated with this address
2567
27
        if (!batch.EraseAddressData(address)) {
2568
0
            WalletLogPrintf("Error: cannot erase address book entry data\n");
2569
0
            return false;
2570
0
        }
2571
2572
        // Delete purpose entry
2573
27
        if (!batch.ErasePurpose(dest)) {
2574
0
            WalletLogPrintf("Error: cannot erase address book entry purpose\n");
2575
0
            return false;
2576
0
        }
2577
2578
        // Delete name entry
2579
27
        if (!batch.EraseName(dest)) {
2580
0
            WalletLogPrintf("Error: cannot erase address book entry name\n");
2581
0
            return false;
2582
0
        }
2583
2584
        // finally, remove it from the map
2585
27
        m_address_book.erase(address);
2586
27
    }
2587
2588
    // All good, signal changes
2589
0
    NotifyAddressBookChanged(address, "", /*is_mine=*/false, AddressPurpose::SEND, CT_DELETED);
2590
27
    return true;
2591
27
}
2592
2593
size_t CWallet::KeypoolCountExternalKeys() const
2594
433
{
2595
433
    AssertLockHeld(cs_wallet);
2596
2597
433
    unsigned int count = 0;
2598
1.37k
    for (auto spk_man : m_external_spk_managers) {
2599
1.37k
        count += spk_man.second->GetKeyPoolSize();
2600
1.37k
    }
2601
2602
433
    return count;
2603
433
}
2604
2605
unsigned int CWallet::GetKeyPoolSize() const
2606
1.36k
{
2607
1.36k
    AssertLockHeld(cs_wallet);
2608
2609
1.36k
    unsigned int count = 0;
2610
7.94k
    for (auto spk_man : GetActiveScriptPubKeyMans()) {
2611
7.94k
        count += spk_man->GetKeyPoolSize();
2612
7.94k
    }
2613
1.36k
    return count;
2614
1.36k
}
2615
2616
bool CWallet::TopUpKeyPool(unsigned int kpSize)
2617
1.00k
{
2618
1.00k
    LOCK(cs_wallet);
2619
1.00k
    bool res = true;
2620
5.53k
    for (auto spk_man : GetActiveScriptPubKeyMans()) {
2621
5.53k
        res &= spk_man->TopUp(kpSize);
2622
5.53k
    }
2623
1.00k
    return res;
2624
1.00k
}
2625
2626
util::Result<CTxDestination> CWallet::GetNewDestination(const OutputType type, const std::string& label)
2627
17.1k
{
2628
17.1k
    LOCK(cs_wallet);
2629
17.1k
    auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
2630
17.1k
    if (!spk_man) {
2631
2
        return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2632
2
    }
2633
2634
17.1k
    auto op_dest = spk_man->GetNewDestination(type);
2635
17.1k
    if (op_dest) {
2636
17.1k
        SetAddressBook(*op_dest, label, AddressPurpose::RECEIVE);
2637
17.1k
    }
2638
2639
17.1k
    return op_dest;
2640
17.1k
}
2641
2642
util::Result<CTxDestination> CWallet::GetNewChangeDestination(const OutputType type)
2643
286
{
2644
286
    LOCK(cs_wallet);
2645
2646
286
    ReserveDestination reservedest(this, type);
2647
286
    auto op_dest = reservedest.GetReservedDestination(true);
2648
286
    if (op_dest) reservedest.KeepDestination();
2649
2650
286
    return op_dest;
2651
286
}
2652
2653
864
void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
2654
256k
    for (auto& entry : mapWallet) {
2655
256k
        CWalletTx& wtx = entry.second;
2656
256k
        if (wtx.m_is_cache_empty) continue;
2657
132
        for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2658
87
            CTxDestination dst;
2659
87
            if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.contains(dst)) {
2660
1
                wtx.MarkDirty();
2661
1
                break;
2662
1
            }
2663
87
        }
2664
46
    }
2665
864
}
2666
2667
void CWallet::ForEachAddrBookEntry(const ListAddrBookFunc& func) const
2668
124
{
2669
124
    AssertLockHeld(cs_wallet);
2670
1.33k
    for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book) {
2671
1.33k
        const auto& entry = item.second;
2672
1.33k
        func(item.first, entry.GetLabel(), entry.IsChange(), entry.purpose);
2673
1.33k
    }
2674
124
}
2675
2676
std::vector<CTxDestination> CWallet::ListAddrBookAddresses(const std::optional<AddrBookFilter>& _filter) const
2677
24
{
2678
24
    AssertLockHeld(cs_wallet);
2679
24
    std::vector<CTxDestination> result;
2680
24
    AddrBookFilter filter = _filter ? *_filter : AddrBookFilter();
2681
200
    ForEachAddrBookEntry([&result, &filter](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
2682
        // Filter by change
2683
200
        if (filter.ignore_change && is_change) return;
2684
        // Filter by label
2685
200
        if (filter.m_op_label && *filter.m_op_label != label) return;
2686
        // All good
2687
43
        result.emplace_back(dest);
2688
43
    });
2689
24
    return result;
2690
24
}
2691
2692
std::set<std::string> CWallet::ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const
2693
38
{
2694
38
    AssertLockHeld(cs_wallet);
2695
38
    std::set<std::string> label_set;
2696
38
    ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label,
2697
489
                             bool _is_change, const std::optional<AddressPurpose>& _purpose) {
2698
489
        if (_is_change) return;
2699
489
        if (!purpose || purpose == _purpose) {
2700
478
            label_set.insert(_label);
2701
478
        }
2702
489
    });
2703
38
    return label_set;
2704
38
}
2705
2706
util::Result<CTxDestination> ReserveDestination::GetReservedDestination(bool internal)
2707
2.11k
{
2708
2.11k
    m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
2709
2.11k
    if (!m_spk_man) {
2710
12
        return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2711
12
    }
2712
2713
2.10k
    if (nIndex == -1) {
2714
2.10k
        int64_t index;
2715
2.10k
        auto op_address = m_spk_man->GetReservedDestination(type, internal, index);
2716
2.10k
        if (!op_address) return op_address;
2717
2.10k
        nIndex = index;
2718
2.10k
        address = *op_address;
2719
2.10k
    }
2720
2.10k
    return address;
2721
2.10k
}
2722
2723
void ReserveDestination::KeepDestination()
2724
3.80k
{
2725
3.80k
    if (nIndex != -1) {
2726
1.99k
        m_spk_man->KeepDestination(nIndex, type);
2727
1.99k
    }
2728
3.80k
    nIndex = -1;
2729
3.80k
    address = CNoDestination();
2730
3.80k
}
2731
2732
void ReserveDestination::ReturnDestination()
2733
3.91k
{
2734
3.91k
    if (nIndex != -1) {
2735
105
        m_spk_man->ReturnDestination(nIndex, fInternal, address);
2736
105
    }
2737
3.91k
    nIndex = -1;
2738
3.91k
    address = CNoDestination();
2739
3.91k
}
2740
2741
util::Result<void> CWallet::DisplayAddress(const CTxDestination& dest)
2742
5
{
2743
5
    CScript scriptPubKey = GetScriptForDestination(dest);
2744
5
    for (const auto& spk_man : GetScriptPubKeyMans(scriptPubKey)) {
2745
5
        auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan *>(spk_man);
2746
5
        if (signer_spk_man == nullptr) {
2747
0
            continue;
2748
0
        }
2749
5
        auto signer{ExternalSignerScriptPubKeyMan::GetExternalSigner()};
2750
5
        if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
2751
5
        return signer_spk_man->DisplayAddress(dest, *signer);
2752
5
    }
2753
0
    return util::Error{_("There is no ScriptPubKeyManager for this address")};
2754
5
}
2755
2756
void CWallet::LoadLockedCoin(const COutPoint& coin, bool persistent)
2757
82
{
2758
82
    AssertLockHeld(cs_wallet);
2759
82
    m_locked_coins.emplace(coin, persistent);
2760
82
}
2761
2762
bool CWallet::LockCoin(const COutPoint& output, bool persist)
2763
80
{
2764
80
    AssertLockHeld(cs_wallet);
2765
80
    LoadLockedCoin(output, persist);
2766
80
    if (persist) {
2767
1
        WalletBatch batch(GetDatabase());
2768
1
        return batch.WriteLockedUTXO(output);
2769
1
    }
2770
79
    return true;
2771
80
}
2772
2773
bool CWallet::UnlockCoin(const COutPoint& output)
2774
13.4k
{
2775
13.4k
    AssertLockHeld(cs_wallet);
2776
13.4k
    auto locked_coin_it = m_locked_coins.find(output);
2777
13.4k
    if (locked_coin_it != m_locked_coins.end()) {
2778
10
        bool persisted = locked_coin_it->second;
2779
10
        m_locked_coins.erase(locked_coin_it);
2780
10
        if (persisted) {
2781
1
            WalletBatch batch(GetDatabase());
2782
1
            return batch.EraseLockedUTXO(output);
2783
1
        }
2784
10
    }
2785
13.4k
    return true;
2786
13.4k
}
2787
2788
bool CWallet::UnlockAllCoins()
2789
4
{
2790
4
    AssertLockHeld(cs_wallet);
2791
4
    bool success = true;
2792
4
    WalletBatch batch(GetDatabase());
2793
52
    for (const auto& [coin, persistent] : m_locked_coins) {
2794
52
        if (persistent) success = success && batch.EraseLockedUTXO(coin);
2795
52
    }
2796
4
    m_locked_coins.clear();
2797
4
    return success;
2798
4
}
2799
2800
bool CWallet::IsLockedCoin(const COutPoint& output) const
2801
468k
{
2802
468k
    AssertLockHeld(cs_wallet);
2803
468k
    return m_locked_coins.contains(output);
2804
468k
}
2805
2806
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
2807
9
{
2808
9
    AssertLockHeld(cs_wallet);
2809
9
    for (const auto& [coin, _] : m_locked_coins) {
2810
4
        vOutpts.push_back(coin);
2811
4
    }
2812
9
}
2813
2814
/**
2815
 * Compute smart timestamp for a transaction being added to the wallet.
2816
 *
2817
 * Logic:
2818
 * - If sending a transaction, assign its timestamp to the current time.
2819
 * - If receiving a transaction outside a block, assign its timestamp to the
2820
 *   current time.
2821
 * - If receiving a transaction during a rescanning process, assign all its
2822
 *   (not already known) transactions' timestamps to the block time.
2823
 * - If receiving a block with a future timestamp, assign all its (not already
2824
 *   known) transactions' timestamps to the current time.
2825
 * - If receiving a block with a past timestamp, before the most recent known
2826
 *   transaction (that we care about), assign all its (not already known)
2827
 *   transactions' timestamps to the same timestamp as that most-recent-known
2828
 *   transaction.
2829
 * - If receiving a block with a past timestamp, but after the most recent known
2830
 *   transaction, assign all its (not already known) transactions' timestamps to
2831
 *   the block time.
2832
 *
2833
 * For more information see CWalletTx::nTimeSmart,
2834
 * https://bitcointalk.org/?topic=54527, or
2835
 * https://github.com/bitcoin/bitcoin/pull/1393.
2836
 */
2837
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
2838
17.6k
{
2839
17.6k
    std::optional<uint256> block_hash;
2840
17.6k
    if (auto* conf = wtx.state<TxStateConfirmed>()) {
2841
14.0k
        block_hash = conf->confirmed_block_hash;
2842
14.0k
    } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
2843
0
        block_hash = conf->conflicting_block_hash;
2844
0
    }
2845
2846
17.6k
    unsigned int nTimeSmart = wtx.nTimeReceived;
2847
17.6k
    if (block_hash) {
2848
14.0k
        int64_t blocktime;
2849
14.0k
        int64_t block_max_time;
2850
14.0k
        if (chain().findBlock(*block_hash, FoundBlock().time(blocktime).maxTime(block_max_time))) {
2851
14.0k
            if (rescanning_old_block) {
2852
4.49k
                nTimeSmart = block_max_time;
2853
9.51k
            } else {
2854
9.51k
                int64_t latestNow = wtx.nTimeReceived;
2855
9.51k
                int64_t latestEntry = 0;
2856
2857
                // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
2858
9.51k
                int64_t latestTolerated = latestNow + 300;
2859
9.51k
                const TxItems& txOrdered = wtxOrdered;
2860
19.0k
                for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2861
18.9k
                    CWalletTx* const pwtx = it->second;
2862
18.9k
                    if (pwtx == &wtx) {
2863
9.51k
                        continue;
2864
9.51k
                    }
2865
9.40k
                    int64_t nSmartTime;
2866
9.40k
                    nSmartTime = pwtx->nTimeSmart;
2867
9.40k
                    if (!nSmartTime) {
2868
0
                        nSmartTime = pwtx->nTimeReceived;
2869
0
                    }
2870
9.40k
                    if (nSmartTime <= latestTolerated) {
2871
9.39k
                        latestEntry = nSmartTime;
2872
9.39k
                        if (nSmartTime > latestNow) {
2873
4
                            latestNow = nSmartTime;
2874
4
                        }
2875
9.39k
                        break;
2876
9.39k
                    }
2877
9.40k
                }
2878
2879
9.51k
                nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2880
9.51k
            }
2881
14.0k
        } else {
2882
0
            WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), block_hash->ToString());
2883
0
        }
2884
14.0k
    }
2885
17.6k
    return nTimeSmart;
2886
17.6k
}
2887
2888
bool CWallet::SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used)
2889
19
{
2890
19
    if (std::get_if<CNoDestination>(&dest))
2891
0
        return false;
2892
2893
19
    if (!used) {
2894
0
        if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false;
2895
0
        return batch.WriteAddressPreviouslySpent(dest, false);
2896
0
    }
2897
2898
19
    LoadAddressPreviouslySpent(dest);
2899
19
    return batch.WriteAddressPreviouslySpent(dest, true);
2900
19
}
2901
2902
void CWallet::LoadAddressPreviouslySpent(const CTxDestination& dest)
2903
26
{
2904
26
    m_address_book[dest].previously_spent = true;
2905
26
}
2906
2907
void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request)
2908
3
{
2909
3
    m_address_book[dest].receive_requests[id] = request;
2910
3
}
2911
2912
bool CWallet::IsAddressPreviouslySpent(const CTxDestination& dest) const
2913
1.65k
{
2914
1.65k
    if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent;
2915
26
    return false;
2916
1.65k
}
2917
2918
std::vector<std::string> CWallet::GetAddressReceiveRequests() const
2919
2
{
2920
2
    std::vector<std::string> values;
2921
3
    for (const auto& [dest, entry] : m_address_book) {
2922
3
        for (const auto& [id, request] : entry.receive_requests) {
2923
3
            values.emplace_back(request);
2924
3
        }
2925
3
    }
2926
2
    return values;
2927
2
}
2928
2929
bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
2930
4
{
2931
4
    if (!batch.WriteAddressReceiveRequest(dest, id, value)) return false;
2932
4
    m_address_book[dest].receive_requests[id] = value;
2933
4
    return true;
2934
4
}
2935
2936
bool CWallet::EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id)
2937
1
{
2938
1
    if (!batch.EraseAddressReceiveRequest(dest, id)) return false;
2939
1
    m_address_book[dest].receive_requests.erase(id);
2940
1
    return true;
2941
1
}
2942
2943
static util::Result<fs::path> GetWalletPath(const std::string& name)
2944
1.41k
{
2945
    // Do some checking on wallet path. It should be either a:
2946
    //
2947
    // 1. Path where a directory can be created.
2948
    // 2. Path to an existing directory.
2949
    // 3. Path to a symlink to a directory.
2950
    // 4. For backwards compatibility, the name of a data file in -walletdir.
2951
1.41k
    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(name));
2952
1.41k
    fs::file_type path_type = fs::symlink_status(wallet_path).type();
2953
1.41k
    if (!(path_type == fs::file_type::not_found || path_type == fs::file_type::directory ||
2954
1.41k
          (path_type == fs::file_type::symlink && fs::is_directory(wallet_path)) ||
2955
1.41k
          (path_type == fs::file_type::regular && fs::PathFromString(name).filename() == fs::PathFromString(name)))) {
2956
4
        return util::Error{Untranslated(strprintf(
2957
4
              "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
2958
4
              "database/log.?????????? files can be stored, a location where such a directory could be created, "
2959
4
              "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
2960
4
              name, fs::quoted(fs::PathToString(GetWalletDir()))))};
2961
4
    }
2962
1.40k
    return wallet_path;
2963
1.41k
}
2964
2965
std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
2966
1.36k
{
2967
1.36k
    const auto& wallet_path = GetWalletPath(name);
2968
1.36k
    if (!wallet_path) {
2969
4
        error_string = util::ErrorString(wallet_path);
2970
4
        status = DatabaseStatus::FAILED_BAD_PATH;
2971
4
        return nullptr;
2972
4
    }
2973
1.35k
    return MakeDatabase(*wallet_path, options, status, error_string);
2974
1.36k
}
2975
2976
bool CWallet::LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings)
2977
954
{
2978
954
    interfaces::Chain* chain = context.chain;
2979
954
    const ArgsManager& args = *Assert(context.args);
2980
2981
954
    if (!args.GetArg("-addresstype", "").empty()) {
2982
73
        std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-addresstype", ""));
2983
73
        if (!parsed) {
2984
0
            error = strprintf(_("Unknown address type '%s'"), args.GetArg("-addresstype", ""));
2985
0
            return false;
2986
0
        }
2987
73
        wallet->m_default_address_type = parsed.value();
2988
73
    }
2989
2990
954
    if (!args.GetArg("-changetype", "").empty()) {
2991
14
        std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-changetype", ""));
2992
14
        if (!parsed) {
2993
0
            error = strprintf(_("Unknown change type '%s'"), args.GetArg("-changetype", ""));
2994
0
            return false;
2995
0
        }
2996
14
        wallet->m_default_change_type = parsed.value();
2997
14
    }
2998
2999
954
    if (const auto arg{args.GetArg("-mintxfee")}) {
3000
13
        std::optional<CAmount> min_tx_fee = ParseMoney(*arg);
3001
13
        if (!min_tx_fee) {
3002
0
            error = AmountErrMsg("mintxfee", *arg);
3003
0
            return false;
3004
13
        } else if (min_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
3005
0
            warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
3006
0
                               _("This is the minimum transaction fee you pay on every transaction."));
3007
0
        }
3008
3009
13
        wallet->m_min_fee = CFeeRate{min_tx_fee.value()};
3010
13
    }
3011
3012
954
    if (const auto arg{args.GetArg("-maxapsfee")}) {
3013
2
        const std::string& max_aps_fee{*arg};
3014
2
        if (max_aps_fee == "-1") {
3015
0
            wallet->m_max_aps_fee = -1;
3016
2
        } else if (std::optional<CAmount> max_fee = ParseMoney(max_aps_fee)) {
3017
2
            if (max_fee.value() > HIGH_APS_FEE) {
3018
0
                warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
3019
0
                                  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
3020
0
            }
3021
2
            wallet->m_max_aps_fee = max_fee.value();
3022
2
        } else {
3023
0
            error = AmountErrMsg("maxapsfee", max_aps_fee);
3024
0
            return false;
3025
0
        }
3026
2
    }
3027
3028
954
    if (const auto arg{args.GetArg("-fallbackfee")}) {
3029
948
        std::optional<CAmount> fallback_fee = ParseMoney(*arg);
3030
948
        if (!fallback_fee) {
3031
0
            error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-fallbackfee", *arg);
3032
0
            return false;
3033
948
        } else if (fallback_fee.value() > HIGH_TX_FEE_PER_KB) {
3034
1
            warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
3035
1
                               _("This is the transaction fee you may pay when fee estimates are not available."));
3036
1
        }
3037
948
        wallet->m_fallback_fee = CFeeRate{fallback_fee.value()};
3038
948
    }
3039
3040
    // Disable fallback fee in case value was set to 0, enable if non-null value
3041
954
    wallet->m_allow_fallback_fee = wallet->m_fallback_fee.GetFeePerK() != 0;
3042
3043
954
    if (const auto arg{args.GetArg("-discardfee")}) {
3044
6
        std::optional<CAmount> discard_fee = ParseMoney(*arg);
3045
6
        if (!discard_fee) {
3046
0
            error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-discardfee", *arg);
3047
0
            return false;
3048
6
        } else if (discard_fee.value() > HIGH_TX_FEE_PER_KB) {
3049
4
            warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
3050
4
                               _("This is the transaction fee you may discard if change is smaller than dust at this level"));
3051
4
        }
3052
6
        wallet->m_discard_rate = CFeeRate{discard_fee.value()};
3053
6
    }
3054
3055
954
    if (const auto arg{args.GetArg("-maxtxfee")}) {
3056
1
        std::optional<CAmount> max_fee = ParseMoney(*arg);
3057
1
        if (!max_fee) {
3058
0
            error = AmountErrMsg("maxtxfee", *arg);
3059
0
            return false;
3060
1
        } else if (max_fee.value() > HIGH_MAX_TX_FEE) {
3061
0
            warnings.push_back(strprintf(_("%s is set very high! Fees this large could be paid on a single transaction."), "-maxtxfee"));
3062
0
        }
3063
3064
1
        if (chain && CFeeRate{max_fee.value(), 1000} < chain->relayMinFee()) {
3065
0
            error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3066
0
                "-maxtxfee", *arg, chain->relayMinFee().ToString());
3067
0
            return false;
3068
0
        }
3069
3070
1
        wallet->m_default_max_tx_fee = max_fee.value();
3071
1
    }
3072
3073
954
    if (const auto arg{args.GetArg("-consolidatefeerate")}) {
3074
0
        if (std::optional<CAmount> consolidate_feerate = ParseMoney(*arg)) {
3075
0
            wallet->m_consolidate_feerate = CFeeRate(*consolidate_feerate);
3076
0
        } else {
3077
0
            error = AmountErrMsg("consolidatefeerate", *arg);
3078
0
            return false;
3079
0
        }
3080
0
    }
3081
3082
954
    if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
3083
2
        warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
3084
2
                           _("The wallet will avoid paying less than the minimum relay fee."));
3085
2
    }
3086
3087
954
    wallet->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3088
954
    wallet->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3089
954
    wallet->m_signal_rbf = args.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3090
3091
954
    wallet->m_keypool_size = std::max(args.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{1});
3092
954
    wallet->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
3093
954
    wallet->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3094
3095
954
    return true;
3096
954
}
3097
3098
std::shared_ptr<CWallet> CWallet::CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings)
3099
603
{
3100
603
    interfaces::Chain* chain = context.chain;
3101
603
    const std::string& walletFile = database->Filename();
3102
3103
603
    const auto start{SteadyClock::now()};
3104
    // TODO: Can't use std::make_shared because we need a custom deleter but
3105
    // should be possible to use std::allocate_shared.
3106
603
    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
3107
3108
603
    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
3109
0
        return nullptr;
3110
0
    }
3111
3112
    // Initialize version key.
3113
603
    if(!WalletBatch(walletInstance->GetDatabase()).WriteVersion(CLIENT_VERSION)) {
3114
0
        error = strprintf(_("Error creating %s: Could not write version metadata."), walletFile);
3115
0
        return nullptr;
3116
0
    }
3117
603
    {
3118
603
        LOCK(walletInstance->cs_wallet);
3119
3120
        // Init with passed flags.
3121
        // Always set the cache upgrade flag as this feature is supported from the beginning.
3122
603
        walletInstance->InitWalletFlags(wallet_creation_flags | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
3123
3124
        // Only descriptor wallets can be created
3125
603
        assert(walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3126
3127
603
        if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) || !(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
3128
385
            walletInstance->SetupDescriptorScriptPubKeyMans();
3129
385
        }
3130
3131
603
        if (chain) {
3132
581
            std::optional<int> tip_height = chain->getHeight();
3133
581
            if (tip_height) {
3134
581
                walletInstance->SetLastBlockProcessed(*tip_height, chain->getBlockHash(*tip_height));
3135
581
            }
3136
581
        }
3137
603
    }
3138
3139
0
    walletInstance->WalletLogPrintf("Wallet completed creation in %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
3140
3141
    // Try to top up keypool. No-op if the wallet is locked.
3142
603
    walletInstance->TopUpKeyPool();
3143
3144
603
    if (chain && !AttachChain(walletInstance, *chain, /*rescan_required=*/false, error, warnings)) {
3145
0
        walletInstance->DisconnectChainNotifications();
3146
0
        return nullptr;
3147
0
    }
3148
3149
603
    return walletInstance;
3150
603
}
3151
3152
std::shared_ptr<CWallet> CWallet::LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings)
3153
351
{
3154
351
    interfaces::Chain* chain = context.chain;
3155
351
    const std::string& walletFile = database->Filename();
3156
3157
351
    const auto start{SteadyClock::now()};
3158
351
    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
3159
3160
351
    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
3161
0
        return nullptr;
3162
0
    }
3163
3164
    // Load wallet
3165
351
    auto nLoadWalletRet = walletInstance->PopulateWalletFromDB(error, warnings);
3166
351
    bool rescan_required = nLoadWalletRet == DBErrors::NEED_RESCAN;
3167
351
    if (nLoadWalletRet != DBErrors::LOAD_OK && nLoadWalletRet != DBErrors::NONCRITICAL_ERROR && !rescan_required) {
3168
1
        return nullptr;
3169
1
    }
3170
3171
350
    if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3172
44
        for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3173
16
            if (spk_man->HavePrivateKeys()) {
3174
0
                warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
3175
0
                break;
3176
0
            }
3177
16
        }
3178
44
    }
3179
3180
350
    walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
3181
3182
    // Try to top up keypool. No-op if the wallet is locked.
3183
350
    walletInstance->TopUpKeyPool();
3184
3185
350
    if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
3186
9
        walletInstance->DisconnectChainNotifications();
3187
9
        return nullptr;
3188
9
    }
3189
3190
341
    WITH_LOCK(walletInstance->cs_wallet, walletInstance->LogStats());
3191
3192
341
    return walletInstance;
3193
350
}
3194
3195
3196
bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings)
3197
885
{
3198
885
    LOCK(walletInstance->cs_wallet);
3199
    // allow setting the chain if it hasn't been set already but prevent changing it
3200
885
    assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
3201
885
    walletInstance->m_chain = &chain;
3202
3203
    // Unless allowed, ensure wallet files are not reused across chains:
3204
885
    if (!gArgs.GetBoolArg("-walletcrosschain", DEFAULT_WALLETCROSSCHAIN)) {
3205
885
        WalletBatch batch(walletInstance->GetDatabase());
3206
885
        CBlockLocator locator;
3207
885
        if (batch.ReadBestBlock(locator) && locator.vHave.size() > 0 && chain.getHeight()) {
3208
            // Wallet is assumed to be from another chain, if genesis block in the active
3209
            // chain differs from the genesis block known to the wallet.
3210
879
            if (chain.getBlockHash(0) != locator.vHave.back()) {
3211
1
                error = Untranslated("Wallet files should not be reused across chains. Restart bitcoind with -walletcrosschain to override.");
3212
1
                return false;
3213
1
            }
3214
879
        }
3215
885
    }
3216
3217
    // Register wallet with validationinterface. It's done before rescan to avoid
3218
    // missing block connections during the rescan.
3219
    // Because of the wallet lock being held, block connection notifications are going to
3220
    // be pending on the validation-side until lock release. Blocks that are connected while the
3221
    // rescan is ongoing will not be processed in the rescan but with the block connected notifications,
3222
    // so the wallet will only be completeley synced after the notifications delivery.
3223
884
    walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
3224
3225
    // If rescan_required = true, rescan_height remains equal to 0
3226
884
    int rescan_height = 0;
3227
884
    if (!rescan_required)
3228
884
    {
3229
884
        WalletBatch batch(walletInstance->GetDatabase());
3230
884
        CBlockLocator locator;
3231
884
        if (batch.ReadBestBlock(locator)) {
3232
883
            if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
3233
878
                rescan_height = *fork_height;
3234
878
            }
3235
883
        }
3236
884
    }
3237
3238
884
    const std::optional<int> tip_height = chain.getHeight();
3239
884
    if (tip_height) {
3240
879
        walletInstance->SetLastBlockProcessedInMem(*tip_height, chain.getBlockHash(*tip_height));
3241
879
    } else {
3242
5
        walletInstance->SetLastBlockProcessedInMem(-1, uint256());
3243
5
    }
3244
3245
884
    if (tip_height && *tip_height != rescan_height)
3246
66
    {
3247
        // No need to read and scan block if block was created before
3248
        // our wallet birthday (as adjusted for block time variability)
3249
66
        std::optional<int64_t> time_first_key = walletInstance->m_birth_time.load();
3250
66
        if (time_first_key) {
3251
66
            FoundBlock found = FoundBlock().height(rescan_height);
3252
66
            chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
3253
66
            if (!found.found) {
3254
                // We were unable to find a block that had a time more recent than our earliest timestamp
3255
                // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
3256
                // current chain tip. Skip rescanning in this case.
3257
0
                rescan_height = *tip_height;
3258
0
            }
3259
66
        }
3260
3261
        // Technically we could execute the code below in any case, but performing the
3262
        // `while` loop below can make startup very slow, so only check blocks on disk
3263
        // if necessary.
3264
66
        if (chain.havePruned() || chain.hasAssumedValidChain()) {
3265
13
            int block_height = *tip_height;
3266
2.24k
            while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
3267
2.23k
                --block_height;
3268
2.23k
            }
3269
3270
13
            if (rescan_height != block_height) {
3271
                // We can't rescan beyond blocks we don't have data for, stop and throw an error.
3272
                // This might happen if a user uses an old wallet within a pruned node
3273
                // or if they ran -disablewallet for a longer time, then decided to re-enable
3274
                // Exit early and print an error.
3275
                // It also may happen if an assumed-valid chain is in use and therefore not
3276
                // all block data is available.
3277
                // If a block is pruned after this check, we will load the wallet,
3278
                // but fail the rescan with a generic error.
3279
3280
8
                error = chain.havePruned() ?
3281
3
                     _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of a pruned node)") :
3282
8
                     strprintf(_(
3283
5
                        "Error loading wallet. Wallet requires blocks to be downloaded, "
3284
5
                        "and software does not currently support loading wallets while "
3285
5
                        "blocks are being downloaded out of order when using assumeutxo "
3286
5
                        "snapshots. Wallet should be able to load successfully after "
3287
5
                        "node sync reaches height %s"), block_height);
3288
8
                return false;
3289
8
            }
3290
13
        }
3291
3292
58
        chain.initMessage(_("Rescanning…"));
3293
58
        walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
3294
3295
58
        {
3296
58
            WalletRescanReserver reserver(*walletInstance);
3297
58
            if (!reserver.reserve()) {
3298
0
                error = _("Failed to acquire rescan reserver during wallet initialization");
3299
0
                return false;
3300
0
            }
3301
58
            ScanResult scan_res = walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, /*max_height=*/{}, reserver, /*fUpdate=*/true, /*save_progress=*/true);
3302
58
            if (ScanResult::SUCCESS != scan_res.status) {
3303
0
                error = _("Failed to rescan the wallet during initialization");
3304
0
                return false;
3305
0
            }
3306
            // Set and update the best block record
3307
            // Set last block scanned as the last block processed as it may be different in case of a reorg.
3308
            // Also save the best block locator because rescanning only updates it intermittently.
3309
58
            walletInstance->SetLastBlockProcessed(*scan_res.last_scanned_height, scan_res.last_scanned_block);
3310
58
        }
3311
58
    }
3312
3313
876
    return true;
3314
884
}
3315
3316
const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
3317
50.7k
{
3318
50.7k
    const auto& address_book_it = m_address_book.find(dest);
3319
50.7k
    if (address_book_it == m_address_book.end()) return nullptr;
3320
37.9k
    if ((!allow_change) && address_book_it->second.IsChange()) {
3321
3
        return nullptr;
3322
3
    }
3323
37.9k
    return &address_book_it->second;
3324
37.9k
}
3325
3326
void CWallet::postInitProcess()
3327
876
{
3328
    // Add wallet transactions that aren't already in a block to mempool
3329
    // Do this here as mempool requires genesis block to be loaded
3330
876
    ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_NO_BROADCAST, /*force=*/true);
3331
3332
    // Update wallet transactions with current mempool transactions.
3333
876
    WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
3334
876
}
3335
3336
bool CWallet::BackupWallet(const std::string& strDest) const
3337
113
{
3338
113
    WITH_LOCK(cs_wallet, WriteBestBlock());
3339
113
    return GetDatabase().Backup(strDest);
3340
113
}
3341
3342
int CWallet::GetTxDepthInMainChain(const CWalletTx& wtx) const
3343
1.24M
{
3344
1.24M
    AssertLockHeld(cs_wallet);
3345
1.24M
    if (auto* conf = wtx.state<TxStateConfirmed>()) {
3346
1.16M
        assert(conf->confirmed_block_height >= 0);
3347
1.16M
        return GetLastBlockHeight() - conf->confirmed_block_height + 1;
3348
1.16M
    } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
3349
4.96k
        assert(conf->conflicting_block_height >= 0);
3350
4.96k
        return -1 * (GetLastBlockHeight() - conf->conflicting_block_height + 1);
3351
78.8k
    } else {
3352
78.8k
        return 0;
3353
78.8k
    }
3354
1.24M
}
3355
3356
int CWallet::GetTxBlocksToMaturity(const CWalletTx& wtx) const
3357
713k
{
3358
713k
    AssertLockHeld(cs_wallet);
3359
3360
713k
    if (!wtx.IsCoinBase()) {
3361
286k
        return 0;
3362
286k
    }
3363
427k
    int chain_depth = GetTxDepthInMainChain(wtx);
3364
427k
    assert(chain_depth >= 0); // coinbase tx should not be conflicted
3365
427k
    return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
3366
427k
}
3367
3368
bool CWallet::IsTxImmatureCoinBase(const CWalletTx& wtx) const
3369
713k
{
3370
713k
    AssertLockHeld(cs_wallet);
3371
3372
    // note GetBlocksToMaturity is 0 for non-coinbase tx
3373
713k
    return GetTxBlocksToMaturity(wtx) > 0;
3374
713k
}
3375
3376
bool CWallet::IsLocked() const
3377
8.05k
{
3378
8.05k
    if (!HasEncryptionKeys()) {
3379
4.37k
        return false;
3380
4.37k
    }
3381
3.67k
    LOCK(cs_wallet);
3382
3.67k
    return vMasterKey.empty();
3383
8.05k
}
3384
3385
bool CWallet::Lock()
3386
84
{
3387
84
    if (!HasEncryptionKeys())
3388
0
        return false;
3389
3390
84
    {
3391
84
        LOCK2(m_relock_mutex, cs_wallet);
3392
84
        if (!vMasterKey.empty()) {
3393
56
            memory_cleanse(vMasterKey.data(), vMasterKey.size() * sizeof(decltype(vMasterKey)::value_type));
3394
56
            vMasterKey.clear();
3395
56
        }
3396
84
    }
3397
3398
84
    NotifyStatusChanged(this);
3399
84
    return true;
3400
84
}
3401
3402
bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
3403
74
{
3404
74
    {
3405
74
        LOCK(cs_wallet);
3406
720
        for (const auto& spk_man_pair : m_spk_managers) {
3407
720
            if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn)) {
3408
0
                return false;
3409
0
            }
3410
720
        }
3411
74
        vMasterKey = vMasterKeyIn;
3412
74
    }
3413
0
    NotifyStatusChanged(this);
3414
74
    return true;
3415
74
}
3416
3417
std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
3418
29.9k
{
3419
29.9k
    std::set<ScriptPubKeyMan*> spk_mans;
3420
59.9k
    for (bool internal : {false, true}) {
3421
239k
        for (OutputType t : OUTPUT_TYPES) {
3422
239k
            auto spk_man = GetScriptPubKeyMan(t, internal);
3423
239k
            if (spk_man) {
3424
136k
                spk_mans.insert(spk_man);
3425
136k
            }
3426
239k
        }
3427
59.9k
    }
3428
29.9k
    return spk_mans;
3429
29.9k
}
3430
3431
bool CWallet::IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const
3432
227
{
3433
729
    for (const auto& [_, ext_spkm] : m_external_spk_managers) {
3434
729
        if (ext_spkm == &spkm) return true;
3435
729
    }
3436
329
    for (const auto& [_, int_spkm] : m_internal_spk_managers) {
3437
329
        if (int_spkm == &spkm) return true;
3438
329
    }
3439
23
    return false;
3440
122
}
3441
3442
std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
3443
4.32k
{
3444
4.32k
    std::set<ScriptPubKeyMan*> spk_mans;
3445
36.6k
    for (const auto& spk_man_pair : m_spk_managers) {
3446
36.6k
        spk_mans.insert(spk_man_pair.second.get());
3447
36.6k
    }
3448
4.32k
    return spk_mans;
3449
4.32k
}
3450
3451
ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
3452
295k
{
3453
295k
    const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
3454
295k
    std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
3455
295k
    if (it == spk_managers.end()) {
3456
108k
        return nullptr;
3457
108k
    }
3458
187k
    return it->second;
3459
295k
}
3460
3461
std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script) const
3462
174k
{
3463
174k
    std::set<ScriptPubKeyMan*> spk_mans;
3464
3465
    // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3466
174k
    const auto& it = m_cached_spks.find(script);
3467
174k
    if (it != m_cached_spks.end()) {
3468
114k
        spk_mans.insert(it->second.begin(), it->second.end());
3469
114k
    }
3470
174k
    SignatureData sigdata;
3471
174k
    Assume(std::all_of(spk_mans.begin(), spk_mans.end(), [&script, &sigdata](ScriptPubKeyMan* spkm) { return spkm->CanProvide(script, sigdata); }));
3472
3473
174k
    return spk_mans;
3474
174k
}
3475
3476
ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
3477
7.43k
{
3478
7.43k
    if (m_spk_managers.contains(id)) {
3479
7.42k
        return m_spk_managers.at(id).get();
3480
7.42k
    }
3481
10
    return nullptr;
3482
7.43k
}
3483
3484
std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
3485
372k
{
3486
372k
    SignatureData sigdata;
3487
372k
    return GetSolvingProvider(script, sigdata);
3488
372k
}
3489
3490
std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
3491
372k
{
3492
    // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3493
372k
    const auto& it = m_cached_spks.find(script);
3494
372k
    if (it != m_cached_spks.end()) {
3495
        // All spkms for a given script must already be able to make a SigningProvider for the script, so just return the first one.
3496
262k
        Assume(it->second.at(0)->CanProvide(script, sigdata));
3497
262k
        return it->second.at(0)->GetSolvingProvider(script);
3498
262k
    }
3499
3500
110k
    return nullptr;
3501
372k
}
3502
3503
std::vector<WalletDescriptor> CWallet::GetWalletDescriptors(const CScript& script) const
3504
36.3k
{
3505
36.3k
    std::vector<WalletDescriptor> descs;
3506
36.3k
    for (const auto spk_man: GetScriptPubKeyMans(script)) {
3507
36.3k
        if (const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man)) {
3508
36.3k
            LOCK(desc_spk_man->cs_desc_man);
3509
36.3k
            descs.push_back(desc_spk_man->GetWalletDescriptor());
3510
36.3k
        }
3511
36.3k
    }
3512
36.3k
    return descs;
3513
36.3k
}
3514
3515
LegacyDataSPKM* CWallet::GetLegacyDataSPKM() const
3516
766
{
3517
766
    if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3518
0
        return nullptr;
3519
0
    }
3520
766
    auto it = m_internal_spk_managers.find(OutputType::LEGACY);
3521
766
    if (it == m_internal_spk_managers.end()) return nullptr;
3522
766
    return dynamic_cast<LegacyDataSPKM*>(it->second);
3523
766
}
3524
3525
void CWallet::AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man)
3526
7.15k
{
3527
    // Add spkm_man to m_spk_managers before calling any method
3528
    // that might access it.
3529
7.15k
    const auto& spkm = m_spk_managers[id] = std::move(spkm_man);
3530
3531
    // Update birth time if needed
3532
7.15k
    MaybeUpdateBirthTime(spkm->GetTimeFirstKey());
3533
7.15k
}
3534
3535
LegacyDataSPKM* CWallet::GetOrCreateLegacyDataSPKM()
3536
659
{
3537
659
    SetupLegacyScriptPubKeyMan();
3538
659
    return GetLegacyDataSPKM();
3539
659
}
3540
3541
void CWallet::SetupLegacyScriptPubKeyMan()
3542
659
{
3543
659
    if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3544
616
        return;
3545
616
    }
3546
3547
43
    Assert(m_database->Format() == "bdb_ro" || m_database->Format() == "sqlite-mock");
3548
43
    std::unique_ptr<ScriptPubKeyMan> spk_manager = std::make_unique<LegacyDataSPKM>(*this);
3549
3550
129
    for (const auto& type : LEGACY_OUTPUT_TYPES) {
3551
129
        m_internal_spk_managers[type] = spk_manager.get();
3552
129
        m_external_spk_managers[type] = spk_manager.get();
3553
129
    }
3554
43
    uint256 id = spk_manager->GetID();
3555
43
    AddScriptPubKeyMan(id, std::move(spk_manager));
3556
43
}
3557
3558
bool CWallet::WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const
3559
2.44k
{
3560
2.44k
    LOCK(cs_wallet);
3561
2.44k
    return cb(vMasterKey);
3562
2.44k
}
3563
3564
bool CWallet::HasEncryptionKeys() const
3565
114k
{
3566
114k
    return !mapMasterKeys.empty();
3567
114k
}
3568
3569
bool CWallet::HaveCryptedKeys() const
3570
1
{
3571
1
    for (const auto& spkm : GetAllScriptPubKeyMans()) {
3572
0
        if (spkm->HaveCryptedKeys()) return true;
3573
0
    }
3574
1
    return false;
3575
1
}
3576
3577
void CWallet::ConnectScriptPubKeyManNotifiers()
3578
1.51k
{
3579
7.60k
    for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
3580
72.5k
        spk_man->NotifyCanGetAddressesChanged.connect([this] {
3581
72.5k
            NotifyCanGetAddressesChanged();
3582
72.5k
        });
3583
7.60k
        spk_man->NotifyFirstKeyTimeChanged.connect([this](const ScriptPubKeyMan*, int64_t time) {
3584
48
            MaybeUpdateBirthTime(time);
3585
48
        });
3586
7.60k
    }
3587
1.51k
}
3588
3589
DescriptorScriptPubKeyMan& CWallet::LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc)
3590
2.50k
{
3591
2.50k
    DescriptorScriptPubKeyMan* spk_manager;
3592
2.50k
    if (IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
3593
8
        spk_manager = new ExternalSignerScriptPubKeyMan(*this, desc, m_keypool_size);
3594
2.49k
    } else {
3595
2.49k
        spk_manager = new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size);
3596
2.49k
    }
3597
2.50k
    AddScriptPubKeyMan(id, std::unique_ptr<ScriptPubKeyMan>(spk_manager));
3598
2.50k
    return *spk_manager;
3599
2.50k
}
3600
3601
DescriptorScriptPubKeyMan& CWallet::SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal)
3602
3.64k
{
3603
3.64k
    AssertLockHeld(cs_wallet);
3604
3.64k
    auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, m_keypool_size));
3605
3.64k
    if (HasEncryptionKeys()) {
3606
138
        if (IsLocked()) {
3607
0
            throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
3608
0
        }
3609
138
        if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, &batch)) {
3610
0
            throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
3611
0
        }
3612
138
    }
3613
3.64k
    spk_manager->SetupDescriptorGeneration(batch, master_key, output_type, internal);
3614
3.64k
    DescriptorScriptPubKeyMan* out = spk_manager.get();
3615
3.64k
    uint256 id = spk_manager->GetID();
3616
3.64k
    AddScriptPubKeyMan(id, std::move(spk_manager));
3617
3.64k
    AddActiveScriptPubKeyManWithDb(batch, id, output_type, internal);
3618
3.64k
    return *out;
3619
3.64k
}
3620
3621
void CWallet::SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key)
3622
454
{
3623
454
    AssertLockHeld(cs_wallet);
3624
908
    for (bool internal : {false, true}) {
3625
3.63k
        for (OutputType t : OUTPUT_TYPES) {
3626
3.63k
            SetupDescriptorScriptPubKeyMan(batch, master_key, t, internal);
3627
3.63k
        }
3628
908
    }
3629
454
}
3630
3631
void CWallet::SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch)
3632
426
{
3633
426
    AssertLockHeld(cs_wallet);
3634
426
    assert(!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER));
3635
    // Make a seed
3636
426
    CKey seed_key = GenerateRandomKey();
3637
426
    CPubKey seed = seed_key.GetPubKey();
3638
426
    assert(seed_key.VerifyPubKey(seed));
3639
3640
    // Get the extended key
3641
426
    CExtKey master_key;
3642
426
    master_key.SetSeed(seed_key);
3643
3644
426
    SetupDescriptorScriptPubKeyMans(batch, master_key);
3645
426
}
3646
3647
void CWallet::SetupDescriptorScriptPubKeyMans()
3648
430
{
3649
430
    AssertLockHeld(cs_wallet);
3650
3651
430
    if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
3652
425
        if (!RunWithinTxn(GetDatabase(), /*process_desc=*/"setup descriptors", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet){
3653
425
            SetupOwnDescriptorScriptPubKeyMans(batch);
3654
425
            return true;
3655
425
        })) throw std::runtime_error("Error: cannot process db transaction for descriptors setup");
3656
425
    } else {
3657
5
        auto signer = ExternalSignerScriptPubKeyMan::GetExternalSigner();
3658
5
        if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
3659
3660
        // TODO: add account parameter
3661
4
        int account = 0;
3662
4
        UniValue signer_res = signer->GetDescriptors(account);
3663
3664
4
        if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3665
3666
4
        WalletBatch batch(GetDatabase());
3667
4
        if (!batch.TxnBegin()) throw std::runtime_error("Error: cannot create db transaction for descriptors import");
3668
3669
5
        for (bool internal : {false, true}) {
3670
5
            const UniValue& descriptor_vals = signer_res.find_value(internal ? "internal" : "receive");
3671
5
            if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3672
17
            for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
3673
17
                const std::string& desc_str = desc_val.getValStr();
3674
17
                FlatSigningProvider keys;
3675
17
                std::string desc_error;
3676
17
                auto descs = Parse(desc_str, keys, desc_error, false);
3677
17
                if (descs.empty()) {
3678
1
                    throw std::runtime_error(std::string(__func__) + ": Invalid descriptor \"" + desc_str + "\" (" + desc_error + ")");
3679
1
                }
3680
16
                auto& desc = descs.at(0);
3681
16
                if (!desc->GetOutputType()) {
3682
0
                    continue;
3683
0
                }
3684
16
                OutputType t =  *desc->GetOutputType();
3685
16
                auto spk_manager = std::unique_ptr<ExternalSignerScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, m_keypool_size));
3686
16
                spk_manager->SetupDescriptor(batch, std::move(desc));
3687
16
                uint256 id = spk_manager->GetID();
3688
16
                AddScriptPubKeyMan(id, std::move(spk_manager));
3689
16
                AddActiveScriptPubKeyManWithDb(batch, id, t, internal);
3690
16
            }
3691
5
        }
3692
3693
        // Ensure imported descriptors are committed to disk
3694
3
        if (!batch.TxnCommit()) throw std::runtime_error("Error: cannot commit db transaction for descriptors import");
3695
3
    }
3696
430
}
3697
3698
void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3699
372
{
3700
372
    WalletBatch batch(GetDatabase());
3701
372
    return AddActiveScriptPubKeyManWithDb(batch, id, type, internal);
3702
372
}
3703
3704
void CWallet::AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal)
3705
4.03k
{
3706
4.03k
    if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
3707
0
        throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
3708
0
    }
3709
4.03k
    LoadActiveScriptPubKeyMan(id, type, internal);
3710
4.03k
}
3711
3712
void CWallet::LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3713
6.13k
{
3714
    // Activating ScriptPubKeyManager for a given output and change type is incompatible with legacy wallets.
3715
    // Legacy wallets have only one ScriptPubKeyManager and it's active for all output and change types.
3716
6.13k
    Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3717
3718
6.13k
    WalletLogPrintf("Setting spkMan to active: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3719
6.13k
    auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3720
6.13k
    auto& spk_mans_other = internal ? m_external_spk_managers : m_internal_spk_managers;
3721
6.13k
    auto spk_man = m_spk_managers.at(id).get();
3722
6.13k
    spk_mans[type] = spk_man;
3723
3724
6.13k
    const auto it = spk_mans_other.find(type);
3725
6.13k
    if (it != spk_mans_other.end() && it->second == spk_man) {
3726
2
        spk_mans_other.erase(type);
3727
2
    }
3728
3729
6.13k
    NotifyCanGetAddressesChanged();
3730
6.13k
}
3731
3732
void CWallet::DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3733
224
{
3734
224
    auto spk_man = GetScriptPubKeyMan(type, internal);
3735
224
    if (spk_man != nullptr && spk_man->GetID() == id) {
3736
1
        WalletLogPrintf("Deactivate spkMan: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3737
1
        WalletBatch batch(GetDatabase());
3738
1
        if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type), internal)) {
3739
0
            throw std::runtime_error(std::string(__func__) + ": erasing active ScriptPubKeyMan id failed");
3740
0
        }
3741
3742
1
        auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3743
1
        spk_mans.erase(type);
3744
1
    }
3745
3746
224
    NotifyCanGetAddressesChanged();
3747
224
}
3748
3749
DescriptorScriptPubKeyMan* CWallet::GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const
3750
847
{
3751
847
    auto spk_man_pair = m_spk_managers.find(desc.id);
3752
3753
847
    if (spk_man_pair != m_spk_managers.end()) {
3754
        // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
3755
21
        DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair->second.get());
3756
21
        if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3757
21
            return spk_manager;
3758
21
        }
3759
21
    }
3760
3761
826
    return nullptr;
3762
847
}
3763
3764
std::optional<bool> CWallet::IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const
3765
25.8k
{
3766
    // only active ScriptPubKeyMan can be internal
3767
25.8k
    if (!GetActiveScriptPubKeyMans().contains(spk_man)) {
3768
8.25k
        return std::nullopt;
3769
8.25k
    }
3770
3771
17.5k
    const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
3772
17.5k
    if (!desc_spk_man) {
3773
0
        throw std::runtime_error(std::string(__func__) + ": unexpected ScriptPubKeyMan type.");
3774
0
    }
3775
3776
17.5k
    LOCK(desc_spk_man->cs_desc_man);
3777
17.5k
    const auto& type = desc_spk_man->GetWalletDescriptor().descriptor->GetOutputType();
3778
17.5k
    assert(type.has_value());
3779
3780
17.5k
    return GetScriptPubKeyMan(*type, /* internal= */ true) == desc_spk_man;
3781
17.5k
}
3782
3783
util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
3784
847
{
3785
847
    AssertLockHeld(cs_wallet);
3786
3787
847
    Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3788
3789
847
    auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3790
847
    if (spk_man) {
3791
21
        WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
3792
21
        if (auto spkm_res = spk_man->UpdateWalletDescriptor(desc); !spkm_res) {
3793
3
            return util::Error{util::ErrorString(spkm_res)};
3794
3
        }
3795
826
    } else {
3796
826
        auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size));
3797
826
        spk_man = new_spk_man.get();
3798
3799
        // Save the descriptor to memory
3800
826
        uint256 id = new_spk_man->GetID();
3801
826
        AddScriptPubKeyMan(id, std::move(new_spk_man));
3802
826
    }
3803
3804
    // Add the private keys to the descriptor
3805
844
    for (const auto& entry : signing_provider.keys) {
3806
648
        const CKey& key = entry.second;
3807
648
        spk_man->AddDescriptorKey(key, key.GetPubKey());
3808
648
    }
3809
3810
    // Top up key pool, the manager will generate new scriptPubKeys internally
3811
844
    if (!spk_man->TopUp()) {
3812
0
        return util::Error{_("Could not top up scriptPubKeys")};
3813
0
    }
3814
3815
    // Apply the label if necessary
3816
    // Note: we disable labels for ranged descriptors
3817
844
    if (!desc.descriptor->IsRange()) {
3818
329
        auto script_pub_keys = spk_man->GetScriptPubKeys();
3819
329
        if (script_pub_keys.empty()) {
3820
0
            return util::Error{_("Could not generate scriptPubKeys (cache is empty)")};
3821
0
        }
3822
3823
329
        if (!internal) {
3824
862
            for (const auto& script : script_pub_keys) {
3825
862
                CTxDestination dest;
3826
862
                if (ExtractDestination(script, dest)) {
3827
674
                    SetAddressBook(dest, label, AddressPurpose::RECEIVE);
3828
674
                }
3829
862
            }
3830
328
        }
3831
329
    }
3832
3833
    // Save the descriptor to DB
3834
844
    spk_man->WriteDescriptor();
3835
3836
    // Break balance caches so that outputs that are now IsMine in already known txs will be included in the balance
3837
844
    MarkDirty();
3838
3839
844
    return std::reference_wrapper(*spk_man);
3840
844
}
3841
3842
bool CWallet::MigrateToSQLite(bilingual_str& error)
3843
43
{
3844
43
    AssertLockHeld(cs_wallet);
3845
3846
43
    WalletLogPrintf("Migrating wallet storage database from BerkeleyDB to SQLite.\n");
3847
3848
43
    if (m_database->Format() == "sqlite") {
3849
0
        error = _("Error: This wallet already uses SQLite");
3850
0
        return false;
3851
0
    }
3852
3853
    // Get all of the records for DB type migration
3854
43
    std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();
3855
43
    std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
3856
43
    std::vector<std::pair<SerializeData, SerializeData>> records;
3857
43
    if (!cursor) {
3858
0
        error = _("Error: Unable to begin reading all records in the database");
3859
0
        return false;
3860
0
    }
3861
43
    DatabaseCursor::Status status = DatabaseCursor::Status::FAIL;
3862
1.22k
    while (true) {
3863
1.22k
        DataStream ss_key{};
3864
1.22k
        DataStream ss_value{};
3865
1.22k
        status = cursor->Next(ss_key, ss_value);
3866
1.22k
        if (status != DatabaseCursor::Status::MORE) {
3867
43
            break;
3868
43
        }
3869
1.18k
        SerializeData key(ss_key.begin(), ss_key.end());
3870
1.18k
        SerializeData value(ss_value.begin(), ss_value.end());
3871
1.18k
        records.emplace_back(key, value);
3872
1.18k
    }
3873
43
    cursor.reset();
3874
43
    batch.reset();
3875
43
    if (status != DatabaseCursor::Status::DONE) {
3876
0
        error = _("Error: Unable to read all records in the database");
3877
0
        return false;
3878
0
    }
3879
3880
    // Close this database and delete the file
3881
43
    fs::path db_path = fs::PathFromString(m_database->Filename());
3882
43
    m_database->Close();
3883
43
    fs::remove(db_path);
3884
3885
    // Generate the path for the location of the migrated wallet
3886
    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
3887
43
    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
3888
3889
    // Make new DB
3890
43
    DatabaseOptions opts;
3891
43
    opts.require_create = true;
3892
43
    opts.require_format = DatabaseFormat::SQLITE;
3893
43
    DatabaseStatus db_status;
3894
43
    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
3895
43
    assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
3896
43
    m_database.reset();
3897
43
    m_database = std::move(new_db);
3898
3899
    // Write existing records into the new DB
3900
43
    batch = m_database->MakeBatch();
3901
43
    bool began = batch->TxnBegin();
3902
43
    assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3903
1.18k
    for (const auto& [key, value] : records) {
3904
1.18k
        if (!batch->Write(std::span{key}, std::span{value})) {
3905
0
            batch->TxnAbort();
3906
0
            m_database->Close();
3907
0
            fs::remove(m_database->Filename());
3908
0
            assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3909
0
        }
3910
1.18k
    }
3911
43
    bool committed = batch->TxnCommit();
3912
43
    assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3913
43
    return true;
3914
43
}
3915
3916
std::optional<MigrationData> CWallet::GetDescriptorsForLegacy(bilingual_str& error) const
3917
40
{
3918
40
    AssertLockHeld(cs_wallet);
3919
3920
40
    LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
3921
40
    if (!Assume(legacy_spkm)) {
3922
        // This shouldn't happen
3923
0
        error = Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"));
3924
0
        return std::nullopt;
3925
0
    }
3926
3927
40
    std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();
3928
40
    if (res == std::nullopt) {
3929
0
        error = _("Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.");
3930
0
        return std::nullopt;
3931
0
    }
3932
40
    return res;
3933
40
}
3934
3935
util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data)
3936
34
{
3937
34
    AssertLockHeld(cs_wallet);
3938
3939
34
    LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
3940
34
    if (!Assume(legacy_spkm)) {
3941
        // This shouldn't happen
3942
0
        return util::Error{Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"))};
3943
0
    }
3944
3945
    // Note: when the legacy wallet has no spendable scripts, it must be empty at the end of the process.
3946
34
    bool has_spendable_material = !data.desc_spkms.empty() || data.master_key.key.IsValid();
3947
3948
    // Get all invalid or non-watched scripts that will not be migrated
3949
34
    std::set<CTxDestination> not_migrated_dests;
3950
34
    for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {
3951
4
        CTxDestination dest;
3952
4
        if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);
3953
4
    }
3954
3955
    // When the legacy wallet has no spendable scripts, the main wallet will be empty, leaving its script cache empty as well.
3956
    // The watch-only and/or solvable wallet(s) will contain the scripts in their respective caches.
3957
34
    if (!data.desc_spkms.empty()) Assume(!m_cached_spks.empty());
3958
34
    if (!data.watch_descs.empty()) Assume(!data.watchonly_wallet->m_cached_spks.empty());
3959
34
    if (!data.solvable_descs.empty()) Assume(!data.solvable_wallet->m_cached_spks.empty());
3960
3961
119
    for (auto& desc_spkm : data.desc_spkms) {
3962
119
        if (m_spk_managers.contains(desc_spkm->GetID())) {
3963
0
            return util::Error{_("Error: Duplicate descriptors created during migration. Your wallet may be corrupted.")};
3964
0
        }
3965
119
        uint256 id = desc_spkm->GetID();
3966
119
        AddScriptPubKeyMan(id, std::move(desc_spkm));
3967
119
    }
3968
3969
    // Remove the LegacyScriptPubKeyMan from disk
3970
34
    if (!legacy_spkm->DeleteRecordsWithDB(local_wallet_batch)) {
3971
0
        return util::Error{_("Error: cannot remove legacy wallet records")};
3972
0
    }
3973
3974
    // Remove the LegacyScriptPubKeyMan from memory
3975
34
    m_spk_managers.erase(legacy_spkm->GetID());
3976
34
    m_external_spk_managers.clear();
3977
34
    m_internal_spk_managers.clear();
3978
3979
    // Setup new descriptors (only if we are migrating any key material)
3980
34
    SetWalletFlagWithDB(local_wallet_batch, WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
3981
34
    if (has_spendable_material && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3982
        // Use the existing master key if we have it
3983
29
        if (data.master_key.key.IsValid()) {
3984
28
            SetupDescriptorScriptPubKeyMans(local_wallet_batch, data.master_key);
3985
28
        } else {
3986
            // Setup with a new seed if we don't.
3987
1
            SetupOwnDescriptorScriptPubKeyMans(local_wallet_batch);
3988
1
        }
3989
29
    }
3990
3991
    // Get best block locator so that we can copy it to the watchonly and solvables
3992
34
    CBlockLocator best_block_locator;
3993
34
    if (!local_wallet_batch.ReadBestBlock(best_block_locator)) {
3994
0
        return util::Error{_("Error: Unable to read wallet's best block locator record")};
3995
0
    }
3996
3997
    // Update m_txos to match the descriptors remaining in this wallet
3998
34
    m_txos.clear();
3999
34
    RefreshAllTXOs();
4000
4001
    // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.
4002
    // We need to go through these in the tx insertion order so that lookups to spends works.
4003
34
    std::vector<Txid> txids_to_delete;
4004
34
    std::unique_ptr<WalletBatch> watchonly_batch;
4005
34
    if (data.watchonly_wallet) {
4006
11
        watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());
4007
11
        if (!watchonly_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.watchonly_wallet->GetName())};
4008
        // Copy the next tx order pos to the watchonly wallet
4009
11
        LOCK(data.watchonly_wallet->cs_wallet);
4010
11
        data.watchonly_wallet->nOrderPosNext = nOrderPosNext;
4011
11
        watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);
4012
        // Write the best block locator to avoid rescanning on reload
4013
11
        if (!watchonly_batch->WriteBestBlock(best_block_locator)) {
4014
0
            return util::Error{_("Error: Unable to write watchonly wallet best block locator record")};
4015
0
        }
4016
11
    }
4017
34
    std::unique_ptr<WalletBatch> solvables_batch;
4018
34
    if (data.solvable_wallet) {
4019
5
        solvables_batch = std::make_unique<WalletBatch>(data.solvable_wallet->GetDatabase());
4020
5
        if (!solvables_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.solvable_wallet->GetName())};
4021
        // Write the best block locator to avoid rescanning on reload
4022
5
        if (!solvables_batch->WriteBestBlock(best_block_locator)) {
4023
0
            return util::Error{_("Error: Unable to write solvable wallet best block locator record")};
4024
0
        }
4025
5
    }
4026
57
    for (const auto& [_pos, wtx] : wtxOrdered) {
4027
        // Check it is the watchonly wallet's
4028
        // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for
4029
57
        bool is_mine = IsMine(*wtx->tx) || IsFromMe(*wtx->tx);
4030
57
        if (data.watchonly_wallet) {
4031
22
            LOCK(data.watchonly_wallet->cs_wallet);
4032
22
            if (data.watchonly_wallet->IsMine(*wtx->tx) || data.watchonly_wallet->IsFromMe(*wtx->tx)) {
4033
                // Add to watchonly wallet
4034
14
                const Txid& hash = wtx->GetHash();
4035
14
                const CWalletTx& to_copy_wtx = *wtx;
4036
14
                if (!data.watchonly_wallet->LoadToWallet(hash, [&](CWalletTx& ins_wtx, bool new_tx) EXCLUSIVE_LOCKS_REQUIRED(data.watchonly_wallet->cs_wallet) {
4037
14
                    if (!new_tx) return false;
4038
14
                    ins_wtx.SetTx(to_copy_wtx.tx);
4039
14
                    ins_wtx.CopyFrom(to_copy_wtx);
4040
14
                    return true;
4041
14
                })) {
4042
0
                    return util::Error{strprintf(_("Error: Could not add watchonly tx %s to watchonly wallet"), wtx->GetHash().GetHex())};
4043
0
                }
4044
14
                watchonly_batch->WriteTx(data.watchonly_wallet->mapWallet.at(hash));
4045
                // Mark as to remove from the migrated wallet only if it does not also belong to it
4046
14
                if (!is_mine) {
4047
11
                    txids_to_delete.push_back(hash);
4048
11
                    continue;
4049
11
                }
4050
14
            }
4051
22
        }
4052
46
        if (!is_mine) {
4053
            // Both not ours and not in the watchonly wallet
4054
0
            return util::Error{strprintf(_("Error: Transaction %s in wallet cannot be identified to belong to migrated wallets"), wtx->GetHash().GetHex())};
4055
0
        }
4056
        // Rewrite the transaction so that anything that may have changed about it in memory also persists to disk
4057
46
        local_wallet_batch.WriteTx(*wtx);
4058
46
    }
4059
4060
    // Do the removes
4061
34
    if (txids_to_delete.size() > 0) {
4062
6
        if (auto res = RemoveTxs(local_wallet_batch, txids_to_delete); !res) {
4063
0
            return util::Error{_("Error: Could not delete watchonly transactions. ") + util::ErrorString(res)};
4064
0
        }
4065
6
    }
4066
4067
    // Pair external wallets with their corresponding db handler
4068
34
    std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;
4069
34
    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet, std::move(watchonly_batch));
4070
34
    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet, std::move(solvables_batch));
4071
4072
    // Write address book entry to disk
4073
58
    auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {
4074
58
        auto address{EncodeDestination(dest)};
4075
58
        if (entry.purpose) batch.WritePurpose(address, PurposeToString(*entry.purpose));
4076
58
        if (entry.label) batch.WriteName(address, *entry.label);
4077
58
        for (const auto& [id, request] : entry.receive_requests) {
4078
0
            batch.WriteAddressReceiveRequest(dest, id, request);
4079
0
        }
4080
58
        if (entry.previously_spent) batch.WriteAddressPreviouslySpent(dest, true);
4081
58
    };
4082
4083
    // Check the address book data in the same way we did for transactions
4084
34
    std::vector<CTxDestination> dests_to_delete;
4085
87
    for (const auto& [dest, record] : m_address_book) {
4086
        // Ensure "receive" entries that are no longer part of the original wallet are transferred to another wallet
4087
        // Entries for everything else ("send") will be cloned to all wallets.
4088
87
        bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);
4089
87
        bool copied = false;
4090
87
        for (auto& [wallet, batch] : wallets_vec) {
4091
59
            LOCK(wallet->cs_wallet);
4092
59
            if (require_transfer && !wallet->IsMine(dest)) continue;
4093
4094
            // Copy the entire address book entry
4095
58
            wallet->m_address_book[dest] = record;
4096
58
            func_store_addr(*batch, dest, record);
4097
4098
58
            copied = true;
4099
            // Only delete 'receive' records that are no longer part of the original wallet
4100
58
            if (require_transfer) {
4101
23
                dests_to_delete.push_back(dest);
4102
23
                break;
4103
23
            }
4104
58
        }
4105
4106
        // Fail immediately if we ever found an entry that was ours and cannot be transferred
4107
        // to any of the created wallets (watch-only, solvable).
4108
        // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.
4109
87
        if (require_transfer && !copied) {
4110
4111
            // Skip invalid/non-watched scripts that will not be migrated
4112
4
            if (not_migrated_dests.contains(dest)) {
4113
4
                dests_to_delete.push_back(dest);
4114
4
                continue;
4115
4
            }
4116
4117
0
            return util::Error{_("Error: Address book data in wallet cannot be identified to belong to migrated wallets")};
4118
4
        }
4119
87
    }
4120
4121
    // Persist external wallets address book entries
4122
34
    for (auto& [wallet, batch] : wallets_vec) {
4123
16
        if (!batch->TxnCommit()) {
4124
0
            return util::Error{strprintf(_("Error: Unable to write data to disk for wallet %s"), wallet->GetName())};
4125
0
        }
4126
16
    }
4127
4128
    // Remove the things to delete in this wallet
4129
34
    if (dests_to_delete.size() > 0) {
4130
27
        for (const auto& dest : dests_to_delete) {
4131
27
            if (!DelAddressBookWithDB(local_wallet_batch, dest)) {
4132
0
                return util::Error{_("Error: Unable to remove watchonly address book data")};
4133
0
            }
4134
27
        }
4135
11
    }
4136
4137
    // If there was no key material in the main wallet, there should be no records on it anymore.
4138
    // This wallet will be discarded at the end of the process. Only wallets that contain the
4139
    // migrated records will be presented to the user.
4140
34
    if (!has_spendable_material) {
4141
3
        if (!m_address_book.empty()) return util::Error{_("Error: Not all address book records were migrated")};
4142
3
        if (!mapWallet.empty()) return util::Error{_("Error: Not all transaction records were migrated")};
4143
3
    }
4144
4145
34
    return {}; // all good
4146
34
}
4147
4148
bool CWallet::CanGrindR() const
4149
144k
{
4150
144k
    return !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
4151
144k
}
4152
4153
// Returns wallet prefix for migration.
4154
// Used to name the backup file and newly created wallets.
4155
// E.g. a watch-only wallet is named "<prefix>_watchonly".
4156
static std::string MigrationPrefixName(CWallet& wallet)
4157
28
{
4158
28
    const std::string& name{wallet.GetName()};
4159
28
    return name.empty() ? "default_wallet" : name;
4160
28
}
4161
4162
bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
4163
40
{
4164
40
    AssertLockHeld(wallet.cs_wallet);
4165
4166
    // Get all of the descriptors from the legacy wallet
4167
40
    std::optional<MigrationData> data = wallet.GetDescriptorsForLegacy(error);
4168
40
    if (data == std::nullopt) return false;
4169
4170
    // Create the watchonly and solvable wallets if necessary
4171
40
    if (data->watch_descs.size() > 0 || data->solvable_descs.size() > 0) {
4172
18
        DatabaseOptions options;
4173
18
        options.require_existing = false;
4174
18
        options.require_create = true;
4175
18
        options.require_format = DatabaseFormat::SQLITE;
4176
4177
18
        WalletContext empty_context;
4178
18
        empty_context.args = context.args;
4179
4180
        // Make the wallets
4181
18
        options.create_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET | WALLET_FLAG_DESCRIPTORS;
4182
18
        if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
4183
1
            options.create_flags |= WALLET_FLAG_AVOID_REUSE;
4184
1
        }
4185
18
        if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
4186
14
            options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;
4187
14
        }
4188
18
        if (data->watch_descs.size() > 0) {
4189
17
            wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts\n");
4190
4191
17
            DatabaseStatus status;
4192
17
            std::vector<bilingual_str> warnings;
4193
17
            std::string wallet_name = MigrationPrefixName(wallet) + "_watchonly";
4194
17
            std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4195
17
            if (!database) {
4196
4
                error = strprintf(_("Wallet file creation failed: %s"), error);
4197
4
                return false;
4198
4
            }
4199
4200
13
            data->watchonly_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4201
13
            if (!data->watchonly_wallet) {
4202
0
                error = _("Error: Failed to create new watchonly wallet");
4203
0
                return false;
4204
0
            }
4205
13
            res.watchonly_wallet = data->watchonly_wallet;
4206
13
            LOCK(data->watchonly_wallet->cs_wallet);
4207
4208
            // Parse the descriptors and add them to the new wallet
4209
37
            for (const auto& [desc_str, creation_time] : data->watch_descs) {
4210
                // Parse the descriptor
4211
37
                FlatSigningProvider keys;
4212
37
                std::string parse_err;
4213
37
                std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
4214
37
                assert(descs.size() == 1); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor or a multipath descriptors
4215
37
                assert(!descs.at(0)->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4216
4217
                // Add to the wallet
4218
37
                WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
4219
37
                if (auto spkm_res = data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
4220
0
                    throw std::runtime_error(util::ErrorString(spkm_res).original);
4221
0
                }
4222
37
            }
4223
4224
            // Add the wallet to settings
4225
13
            UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4226
13
        }
4227
14
        if (data->solvable_descs.size() > 0) {
4228
7
            wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts\n");
4229
4230
7
            DatabaseStatus status;
4231
7
            std::vector<bilingual_str> warnings;
4232
7
            std::string wallet_name = MigrationPrefixName(wallet) + "_solvables";
4233
7
            std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4234
7
            if (!database) {
4235
2
                error = strprintf(_("Wallet file creation failed: %s"), error);
4236
2
                return false;
4237
2
            }
4238
4239
5
            data->solvable_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4240
5
            if (!data->solvable_wallet) {
4241
0
                error = _("Error: Failed to create new watchonly wallet");
4242
0
                return false;
4243
0
            }
4244
5
            res.solvables_wallet = data->solvable_wallet;
4245
5
            LOCK(data->solvable_wallet->cs_wallet);
4246
4247
            // Parse the descriptors and add them to the new wallet
4248
12
            for (const auto& [desc_str, creation_time] : data->solvable_descs) {
4249
                // Parse the descriptor
4250
12
                FlatSigningProvider keys;
4251
12
                std::string parse_err;
4252
12
                std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
4253
12
                assert(descs.size() == 1); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor or a multipath descriptors
4254
12
                assert(!descs.at(0)->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4255
4256
                // Add to the wallet
4257
12
                WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
4258
12
                if (auto spkm_res = data->solvable_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
4259
0
                    throw std::runtime_error(util::ErrorString(spkm_res).original);
4260
0
                }
4261
12
            }
4262
4263
            // Add the wallet to settings
4264
5
            UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4265
5
        }
4266
14
    }
4267
4268
    // Add the descriptors to wallet, remove LegacyScriptPubKeyMan, and cleanup txs and address book data
4269
34
    return RunWithinTxn(wallet.GetDatabase(), /*process_desc=*/"apply migration process", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet){
4270
34
        if (auto res_migration = wallet.ApplyMigrationData(batch, *data); !res_migration) {
4271
0
            error = util::ErrorString(res_migration);
4272
0
            return false;
4273
0
        }
4274
34
        wallet.WalletLogPrintf("Wallet migration complete.\n");
4275
34
        return true;
4276
34
    });
4277
40
}
4278
4279
util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context)
4280
49
{
4281
49
    std::vector<bilingual_str> warnings;
4282
49
    bilingual_str error;
4283
4284
    // The only kind of wallets that could be loaded are descriptor ones, which don't need to be migrated.
4285
49
    if (auto wallet = GetWallet(context, wallet_name)) {
4286
1
        assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
4287
1
        return util::Error{_("Error: This wallet is already a descriptor wallet")};
4288
48
    } else {
4289
        // Check if the wallet is BDB
4290
48
        const auto& wallet_path = GetWalletPath(wallet_name);
4291
48
        if (!wallet_path) {
4292
0
            return util::Error{util::ErrorString(wallet_path)};
4293
0
        }
4294
48
        if (!fs::exists(*wallet_path)) {
4295
1
            return util::Error{_("Error: Wallet does not exist")};
4296
1
        }
4297
47
        if (!IsBDBFile(BDBDataFile(*wallet_path))) {
4298
1
            return util::Error{_("Error: This wallet is already a descriptor wallet")};
4299
1
        }
4300
47
    }
4301
4302
    // Load the wallet but only in the context of this function.
4303
    // No signals should be connected nor should anything else be aware of this wallet
4304
46
    WalletContext empty_context;
4305
46
    empty_context.args = context.args;
4306
46
    DatabaseOptions options;
4307
46
    options.require_existing = true;
4308
46
    options.require_format = DatabaseFormat::BERKELEY_RO;
4309
46
    DatabaseStatus status;
4310
46
    std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4311
46
    if (!database) {
4312
0
        return util::Error{Untranslated("Wallet file verification failed.") + Untranslated(" ") + error};
4313
0
    }
4314
4315
    // Make the local wallet
4316
46
    std::shared_ptr<CWallet> local_wallet = CWallet::LoadExisting(empty_context, wallet_name, std::move(database), error, warnings);
4317
46
    if (!local_wallet) {
4318
0
        return util::Error{Untranslated("Wallet loading failed.") + Untranslated(" ") + error};
4319
0
    }
4320
4321
46
    return MigrateLegacyToDescriptor(std::move(local_wallet), passphrase, context);
4322
46
}
4323
4324
util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context)
4325
46
{
4326
46
    MigrationResult res;
4327
46
    bilingual_str error;
4328
46
    std::vector<bilingual_str> warnings;
4329
4330
46
    DatabaseOptions options;
4331
46
    options.require_existing = true;
4332
46
    DatabaseStatus status;
4333
4334
46
    const std::string wallet_name = local_wallet->GetName();
4335
4336
    // Before anything else, check if there is something to migrate.
4337
46
    if (local_wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4338
0
        return util::Error{_("Error: This wallet is already a descriptor wallet")};
4339
0
    }
4340
4341
    // Make a backup of the DB in the wallet's directory with a unique filename
4342
    // using the wallet name and current timestamp. The backup filename is based
4343
    // on the name of the parent directory containing the wallet data in most
4344
    // cases, but in the case where the wallet name is a path to a data file,
4345
    // the name of the data file is used, and in the case where the wallet name
4346
    // is blank, "default_wallet" is used.
4347
46
    const std::string backup_prefix = wallet_name.empty() ? MigrationPrefixName(*local_wallet) : [&] {
4348
        // fs::weakly_canonical resolves relative specifiers and remove trailing slashes.
4349
42
        const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(wallet_name));
4350
42
        return fs::PathToString(legacy_wallet_path.filename());
4351
42
    }();
4352
4353
46
    fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", backup_prefix, GetTime()));
4354
46
    fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
4355
46
    if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
4356
0
        return util::Error{_("Error: Unable to make a backup of your wallet")};
4357
0
    }
4358
46
    res.backup_path = backup_path;
4359
4360
46
    bool success = false;
4361
4362
    // Unlock the wallet if needed
4363
46
    if (local_wallet->IsLocked() && !local_wallet->Unlock(passphrase)) {
4364
3
        if (passphrase.find('\0') == std::string::npos) {
4365
2
            return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase was not provided or was incorrect.")};
4366
2
        } else {
4367
1
            return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase entered was incorrect. "
4368
1
                                            "The passphrase contains a null character (ie - a zero byte). "
4369
1
                                            "If this passphrase was set with a version of this software prior to 25.0, "
4370
1
                                            "please try again with only the characters up to — but not including — "
4371
1
                                            "the first null character.")};
4372
1
        }
4373
3
    }
4374
4375
    // Indicates whether the current wallet is empty after migration.
4376
    // Notes:
4377
    // When non-empty: the local wallet becomes the main spendable wallet.
4378
    // When empty: The local wallet is excluded from the result, as the
4379
    //             user does not expect an empty spendable wallet after
4380
    //             migrating only watch-only scripts.
4381
43
    bool empty_local_wallet = false;
4382
4383
43
    {
4384
43
        LOCK(local_wallet->cs_wallet);
4385
        // First change to using SQLite
4386
43
        if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
4387
4388
        // Do the migration of keys and scripts for non-empty wallets, and cleanup if it fails
4389
43
        if (HasLegacyRecords(*local_wallet)) {
4390
40
            success = DoMigration(*local_wallet, context, error, res);
4391
            // No scripts mean empty wallet after migration
4392
40
            empty_local_wallet = local_wallet->GetAllScriptPubKeyMans().empty();
4393
40
        } else {
4394
            // Make sure that descriptors flag is actually set
4395
3
            local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
4396
3
            success = true;
4397
3
        }
4398
43
    }
4399
4400
    // In case of loading failure, we need to remember the wallet files we have created to remove.
4401
    // A `set` is used as it may be populated with the same wallet directory paths multiple times,
4402
    // both before and after loading. This ensures the set is complete even if one of the wallets
4403
    // fails to load.
4404
0
    std::set<fs::path> wallet_files_to_remove;
4405
43
    std::set<fs::path> wallet_empty_dirs_to_remove;
4406
4407
    // Helper to track wallet files and directories for cleanup on failure.
4408
    // Only directories of wallets created during migration (not the main wallet) are tracked.
4409
58
    auto track_for_cleanup = [&](const CWallet& wallet) {
4410
58
        const auto files = wallet.GetDatabase().Files();
4411
58
        wallet_files_to_remove.insert(files.begin(), files.end());
4412
58
        if (wallet.GetName() != wallet_name) {
4413
            // If this isn’t the main wallet, mark its directory for removal.
4414
            // This applies to the watch-only and solvable wallets.
4415
            // Wallets stored directly as files in the top-level directory
4416
            // (e.g. default unnamed wallets) don’t have a removable parent directory.
4417
18
            wallet_empty_dirs_to_remove.insert(fs::PathFromString(wallet.GetDatabase().Filename()).parent_path());
4418
18
        }
4419
58
    };
4420
4421
4422
43
    if (success) {
4423
37
        Assume(!res.wallet); // We will set it here.
4424
        // Check if the local wallet is empty after migration
4425
37
        if (empty_local_wallet) {
4426
            // This wallet has no records. We can safely remove it.
4427
3
            std::vector<fs::path> paths_to_remove = local_wallet->GetDatabase().Files();
4428
3
            local_wallet.reset();
4429
6
            for (const auto& path_to_remove : paths_to_remove) fs::remove(path_to_remove);
4430
3
        }
4431
4432
37
        LogInfo("Loading new wallets after migration...\n");
4433
        // Migration successful, load all the migrated wallets.
4434
107
        for (std::shared_ptr<CWallet>* wallet_ptr : {&local_wallet, &res.watchonly_wallet, &res.solvables_wallet}) {
4435
107
            if (success && *wallet_ptr) {
4436
50
                std::shared_ptr<CWallet>& wallet = *wallet_ptr;
4437
                // Track db path and load wallet
4438
50
                track_for_cleanup(*wallet);
4439
50
                assert(wallet.use_count() == 1);
4440
50
                std::string wallet_name = wallet->GetName();
4441
50
                wallet.reset();
4442
50
                wallet = LoadWallet(context, wallet_name, /*load_on_start=*/std::nullopt, options, status, error, warnings);
4443
50
                if (!wallet) {
4444
2
                    LogError("Failed to load wallet '%s' after migration. Rolling back migration to preserve consistency. "
4445
2
                             "Error cause: %s\n", wallet_name, error.original);
4446
2
                    success = false;
4447
2
                    break;
4448
2
                }
4449
4450
                // Set the first successfully loaded wallet as the main one.
4451
                // The loop order is intentional and must always start with the local wallet.
4452
48
                if (!res.wallet) {
4453
35
                    res.wallet_name = wallet->GetName();
4454
35
                    res.wallet = std::move(wallet);
4455
35
                }
4456
48
            }
4457
107
        }
4458
37
    }
4459
43
    if (!success) {
4460
        // Make list of wallets to cleanup
4461
8
        std::vector<std::shared_ptr<CWallet>> created_wallets;
4462
8
        if (local_wallet) created_wallets.push_back(std::move(local_wallet));
4463
8
        if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));
4464
8
        if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));
4465
4466
        // Get the directories to remove after unloading
4467
8
        for (std::shared_ptr<CWallet>& wallet : created_wallets) {
4468
8
            track_for_cleanup(*wallet);
4469
8
        }
4470
4471
        // Unload the wallets
4472
8
        for (std::shared_ptr<CWallet>& w : created_wallets) {
4473
8
            if (w->HaveChain()) {
4474
                // Unloading for wallets that were loaded for normal use
4475
0
                if (!RemoveWallet(context, w, /*load_on_start=*/false)) {
4476
0
                    error += _("\nUnable to cleanup failed migration");
4477
0
                    return util::Error{error};
4478
0
                }
4479
0
                WaitForDeleteWallet(std::move(w));
4480
8
            } else {
4481
                // Unloading for wallets in local context
4482
8
                assert(w.use_count() == 1);
4483
8
                w.reset();
4484
8
            }
4485
8
        }
4486
4487
        // First, delete the db files we have created throughout this process and nothing else
4488
20
        for (const fs::path& file : wallet_files_to_remove) {
4489
20
            fs::remove(file);
4490
20
        }
4491
4492
        // Second, delete the created wallet directories and nothing else. They must be empty at this point.
4493
8
        for (const fs::path& dir : wallet_empty_dirs_to_remove) {
4494
2
            Assume(fs::is_empty(dir));
4495
2
            fs::remove(dir);
4496
2
        }
4497
4498
        // Restore the backup
4499
        // Convert the backup file to the wallet db file by renaming it and moving it into the wallet's directory.
4500
8
        bilingual_str restore_error;
4501
8
        const auto& ptr_wallet = RestoreWallet(context, backup_path, wallet_name, /*load_on_start=*/std::nullopt, status, restore_error, warnings, /*load_after_restore=*/false, /*allow_unnamed=*/true);
4502
8
        if (!restore_error.empty()) {
4503
0
            error += restore_error + _("\nUnable to restore backup of wallet.");
4504
0
            return util::Error{error};
4505
0
        }
4506
        // Verify that the legacy wallet is not loaded after restoring from the backup.
4507
8
        assert(!ptr_wallet);
4508
4509
8
        return util::Error{error};
4510
8
    }
4511
35
    return res;
4512
43
}
4513
4514
void CWallet::CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
4515
80.8k
{
4516
474k
    for (const auto& script : spks) {
4517
474k
        m_cached_spks[script].push_back(spkm);
4518
474k
    }
4519
80.8k
}
4520
4521
void CWallet::TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
4522
80.8k
{
4523
    // Update scriptPubKey cache
4524
80.8k
    CacheNewScriptPubKeys(spks, spkm);
4525
80.8k
}
4526
4527
std::set<CExtPubKey> CWallet::GetActiveHDPubKeys() const
4528
7
{
4529
7
    AssertLockHeld(cs_wallet);
4530
4531
7
    Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
4532
4533
7
    std::set<CExtPubKey> active_xpubs;
4534
23
    for (const auto& spkm : GetActiveScriptPubKeyMans()) {
4535
23
        const DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
4536
23
        assert(desc_spkm);
4537
23
        LOCK(desc_spkm->cs_desc_man);
4538
23
        WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();
4539
4540
23
        std::set<CPubKey> desc_pubkeys;
4541
23
        std::set<CExtPubKey> desc_xpubs;
4542
23
        w_desc.descriptor->GetPubKeys(desc_pubkeys, desc_xpubs);
4543
23
        active_xpubs.merge(std::move(desc_xpubs));
4544
23
    }
4545
7
    return active_xpubs;
4546
7
}
4547
4548
std::optional<CKey> CWallet::GetKey(const CKeyID& keyid) const
4549
8
{
4550
8
    Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
4551
4552
8
    for (const auto& spkm : GetAllScriptPubKeyMans()) {
4553
8
        const DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
4554
8
        assert(desc_spkm);
4555
8
        LOCK(desc_spkm->cs_desc_man);
4556
8
        if (std::optional<CKey> key = desc_spkm->GetKey(keyid)) {
4557
7
            return key;
4558
7
        }
4559
8
    }
4560
1
    return std::nullopt;
4561
8
}
4562
4563
void CWallet::WriteBestBlock() const
4564
13.5k
{
4565
13.5k
    AssertLockHeld(cs_wallet);
4566
4567
13.5k
    if (!m_last_block_processed.IsNull()) {
4568
13.5k
        CBlockLocator loc;
4569
13.5k
        chain().findBlock(m_last_block_processed, FoundBlock().locator(loc));
4570
4571
13.5k
        if (!loc.IsNull()) {
4572
13.5k
            WalletBatch batch(GetDatabase());
4573
13.5k
            batch.WriteBestBlock(loc);
4574
13.5k
        }
4575
13.5k
    }
4576
13.5k
}
4577
4578
void CWallet::RefreshTXOsFromTx(const CWalletTx& wtx)
4579
35.1k
{
4580
35.1k
    AssertLockHeld(cs_wallet);
4581
183k
    for (uint32_t i = 0; i < wtx.tx->vout.size(); ++i) {
4582
148k
        const CTxOut& txout = wtx.tx->vout.at(i);
4583
148k
        if (!IsMine(txout)) continue;
4584
60.5k
        COutPoint outpoint(wtx.GetHash(), i);
4585
60.5k
        if (m_txos.contains(outpoint)) {
4586
44.0k
        } else {
4587
44.0k
            m_txos.emplace(outpoint, WalletTXO{wtx, txout});
4588
44.0k
        }
4589
60.5k
    }
4590
35.1k
}
4591
4592
void CWallet::RefreshAllTXOs()
4593
689
{
4594
689
    AssertLockHeld(cs_wallet);
4595
2.26k
    for (const auto& [_, wtx] : mapWallet) {
4596
2.26k
        RefreshTXOsFromTx(wtx);
4597
2.26k
    }
4598
689
}
4599
4600
std::optional<WalletTXO> CWallet::GetTXO(const COutPoint& outpoint) const
4601
176k
{
4602
176k
    AssertLockHeld(cs_wallet);
4603
176k
    const auto& it = m_txos.find(outpoint);
4604
176k
    if (it == m_txos.end()) {
4605
166k
        return std::nullopt;
4606
166k
    }
4607
10.3k
    return it->second;
4608
176k
}
4609
4610
void CWallet::DisconnectChainNotifications()
4611
881
{
4612
881
    if (m_chain_notifications_handler) {
4613
880
        m_chain_notifications_handler->disconnect();
4614
880
        chain().waitForNotifications();
4615
880
        m_chain_notifications_handler.reset();
4616
880
    }
4617
881
}
4618
4619
} // namespace wallet