Coverage Report

Created: 2025-06-10 13:21

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