Coverage Report

Created: 2026-10-19 15:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/test/wallet_tests.cpp
Line
Count
Source
1
// Copyright (c) 2012-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <wallet/wallet.h>
6
7
#include <array>
8
#include <cstddef>
9
#include <cstdint>
10
#include <future>
11
#include <limits>
12
#include <memory>
13
#include <optional>
14
#include <stdexcept>
15
#include <string>
16
#include <utility>
17
#include <vector>
18
19
#include <addresstype.h>
20
#include <chain.h>
21
#include <consensus/tx_verify.h>
22
#include <consensus/validation.h>
23
#include <interfaces/chain.h>
24
#include <key_io.h>
25
#include <node/types.h>
26
#include <policy/feerate.h>
27
#include <policy/policy.h>
28
#include <rpc/server.h>
29
#include <script/descriptor.h>
30
#include <script/solver.h>
31
#include <test/util/common.h>
32
#include <test/util/logging.h>
33
#include <test/util/random.h>
34
#include <test/util/setup_common.h>
35
#include <test/util/time.h>
36
#include <util/check.h>
37
#include <util/strencodings.h>
38
#include <util/translation.h>
39
#include <validation.h>
40
#include <validationinterface.h>
41
#include <wallet/coincontrol.h>
42
#include <wallet/context.h>
43
#include <wallet/imports.h>
44
#include <wallet/receive.h>
45
#include <wallet/spend.h>
46
#include <wallet/test/util.h>
47
#include <wallet/test/wallet_test_fixture.h>
48
49
#include <boost/test/unit_test.hpp>
50
51
namespace wallet {
52
53
// Ensure that fee levels defined in the wallet are at least as high
54
// as the default levels for node policy.
55
static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
56
static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
57
58
BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
59
60
static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
61
5
{
62
5
    CMutableTransaction mtx;
63
5
    mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
64
5
    mtx.vin.push_back({CTxIn{from.GetHash(), index}});
65
5
    FillableSigningProvider keystore;
66
5
    keystore.AddKey(key);
67
5
    std::map<COutPoint, Coin> coins;
68
5
    coins[mtx.vin[0].prevout].out = from.vout[index];
69
5
    std::map<int, bilingual_str> input_errors;
70
5
    BOOST_CHECK(SignTransaction(mtx, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors));
71
5
    return mtx;
72
5
}
73
74
static bool BroadcastTestSimpleSpend(interfaces::Chain& chain, ChainstateManager& chainman, const CMutableTransaction& tx, std::string& error)
75
2
{
76
2
    const auto tx_ref{MakeTransactionRef(tx)};
77
2
    const auto tx_sigops = WITH_LOCK(::cs_main, return GetTransactionSigOpCost(
78
2
                                                    *tx_ref, chainman.ActiveChainstate().CoinsTip(), STANDARD_SCRIPT_VERIFY_FLAGS));
79
2
    const auto tx_vsize{GetVirtualTransactionSize(*tx_ref, tx_sigops, nBytesPerSigOp)};
80
2
    const auto tx_feerate{CFeeRate{DEFAULT_TRANSACTION_MAXFEE, static_cast<int32_t>(tx_vsize)}};
81
    // TestSimpleSpend pays a high fee; use a limit just above its feerate.
82
2
    const auto tx_feerate_limit{CFeeRate{tx_feerate.GetFeePerK() + 1}};
83
2
    return chain.broadcastTransaction(tx_ref, DEFAULT_TRANSACTION_MAXFEE, tx_feerate_limit, node::TxBroadcast::MEMPOOL_NO_BROADCAST, error);
84
2
}
85
86
BOOST_AUTO_TEST_CASE(reject_invalid_descriptor_ranges)
87
1
{
88
1
    const int height{*Assert(m_node.chain->getHeight())};
89
1
    {
90
1
        LOCK(m_wallet.cs_wallet);
91
1
        m_wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
92
1
        m_wallet.SetLastBlockProcessed(height, m_node.chain->getBlockHash(height));
93
1
    }
94
95
1
    CExtKey ext_key;
96
1
    ext_key.SetSeed(std::array<std::byte, 32>{});
97
1
    const std::string descriptor_without_checksum{"wpkh(" + EncodeExtKey(ext_key) + "/*)"};
98
1
    const std::string descriptor{descriptor_without_checksum + "#" + GetDescriptorChecksum(descriptor_without_checksum)};
99
100
1
    const std::array invalid_ranges{
101
1
        std::pair{std::pair<int64_t, int64_t>{2, 1}, "Range specified as [begin,end] must not have begin after end"},
102
1
        std::pair{std::pair<int64_t, int64_t>{std::numeric_limits<int64_t>::max(), 0}, "Range specified as [begin,end] must not have begin after end"},
103
1
        std::pair{std::pair<int64_t, int64_t>{-1, 10}, "Range should be greater or equal than 0"},
104
1
        std::pair{std::pair<int64_t, int64_t>{0, 1'000'000}, "Range is too large"},
105
1
        std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()}, "End of range is too high"},
106
1
        std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31}, "End of range is too high"},
107
1
    };
108
109
6
    for (const auto& [range, expected_error] : invalid_ranges) {
110
6
        std::vector requests{ImportDescriptorRequest{
111
6
            .descriptor = descriptor,
112
6
            .label = {},
113
6
            .timestamp = 0,
114
6
            .active = false,
115
6
            .internal = std::nullopt,
116
6
            .range = range,
117
6
            .next_index = std::nullopt,
118
6
        }};
119
6
        const auto results{ProcessDescriptorsImport(m_wallet, requests)};
120
6
        BOOST_REQUIRE_EQUAL(results.size(), 1U);
121
6
        BOOST_REQUIRE(results.front().error.has_value());
122
6
        BOOST_CHECK(results.front().error->wallet_error.code == WalletErrorCode::InvalidParameter);
123
6
        BOOST_CHECK_EQUAL(results.front().error->wallet_error.message.original, expected_error);
124
6
        BOOST_CHECK(!results.front().error->is_general_error);
125
6
    }
126
1
}
127
128
namespace {
129
struct EncryptionFailureSetup : TestingSetup {
130
    WalletContext context;
131
    FaultInjectingDatabase* fail_db{nullptr};
132
    std::shared_ptr<CWallet> wallet;
133
    FakeNodeClock clock; // Frozen time makes EncryptMasterKey use the default KDF iteration count
134
135
    EncryptionFailureSetup()
136
7
    {
137
7
        context.args = &m_args;
138
7
        m_args.ForceSetArg("-keypool", "1"); // Failure injection does not depend on keypool depth
139
7
        context.chain = m_node.chain.get();
140
7
        RecreateWallet(WALLET_FLAG_DESCRIPTORS);
141
7
    }
142
143
    void RecreateWallet(uint64_t create_flags)
144
12
    {
145
12
        if (wallet) TestUnloadWallet(std::move(wallet));
146
12
        auto database{std::make_unique<FaultInjectingDatabase>()};
147
12
        fail_db = database.get();
148
12
        wallet = TestCreateWallet(std::move(database), context, create_flags);
149
12
    }
150
151
7
    ~EncryptionFailureSetup() { TestUnloadWallet(std::move(wallet)); }
152
};
153
} // namespace
154
155
BOOST_FIXTURE_TEST_CASE(encrypt_wallet_master_key_write_failure, EncryptionFailureSetup)
156
1
{
157
1
    AddKey(*wallet, GenerateRandomKey());
158
159
1
    fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
160
2
    for (bool success : {false, true}) {
161
2
        BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
162
2
        BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
163
2
        BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
164
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::MASTER_KEY), success);
165
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY), !success);
166
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY), success);
167
2
    }
168
1
}
169
170
BOOST_FIXTURE_TEST_CASE(encrypt_wallet_commit_failure, EncryptionFailureSetup)
171
1
{
172
1
    AddKey(*wallet, GenerateRandomKey());
173
174
1
    fail_db->FailNextCommit(); // The injected failure affects only the first attempt
175
1
    test_only_CheckFailuresAreExceptionsNotAborts mock_checks; // Keep abort regressions observable
176
1
    BOOST_CHECK(!wallet->EncryptWallet("passphrase"));
177
1
    BOOST_CHECK(!wallet->HasEncryptionKeys());
178
1
    BOOST_CHECK(!wallet->HaveCryptedKeys());
179
1
    BOOST_CHECK(!fail_db->HasRecordType(DBKeys::MASTER_KEY));
180
1
    BOOST_CHECK( fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY));
181
1
    BOOST_CHECK(!fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY));
182
1
    BOOST_CHECK( wallet->EncryptWallet("passphrase"));
183
1
    BOOST_CHECK( wallet->HasEncryptionKeys());
184
1
    BOOST_CHECK( wallet->HaveCryptedKeys());
185
1
    BOOST_CHECK( fail_db->HasRecordType(DBKeys::MASTER_KEY));
186
1
    BOOST_CHECK(!fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY));
187
1
    BOOST_CHECK( fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY));
188
1
}
189
190
BOOST_FIXTURE_TEST_CASE(encrypt_wallet_descriptor_key_write_failure, EncryptionFailureSetup)
191
1
{
192
1
    AddKey(*wallet, GenerateRandomKey());
193
194
1
    fail_db->FailNextWrite(DBKeys::WALLETDESCRIPTORCKEY, /*match_skip_count=*/1); // Only one write fails
195
2
    for (bool success : {false, true}) {
196
2
        BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
197
2
        BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
198
2
        BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
199
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::MASTER_KEY), success);
200
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY), !success);
201
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY), success);
202
2
    }
203
1
}
204
205
BOOST_FIXTURE_TEST_CASE(encrypt_wallet_descriptor_key_erase_failure, EncryptionFailureSetup)
206
1
{
207
1
    AddKey(*wallet, GenerateRandomKey());
208
209
1
    fail_db->FailNextErase(DBKeys::WALLETDESCRIPTORKEY); // Only one erase fails
210
2
    for (bool success : {false, true}) {
211
2
        BOOST_CHECK_EQUAL(wallet->EncryptWallet("passphrase"), success);
212
2
        BOOST_CHECK_EQUAL(wallet->HasEncryptionKeys(), success);
213
2
        BOOST_CHECK_EQUAL(wallet->HaveCryptedKeys(), success);
214
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::MASTER_KEY), success);
215
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY), !success);
216
2
        BOOST_CHECK_EQUAL(fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY), success);
217
2
    }
218
1
}
219
220
BOOST_FIXTURE_TEST_CASE(change_passphrase_master_key_write_failure, EncryptionFailureSetup)
221
1
{
222
1
    AddKey(*wallet, GenerateRandomKey());
223
1
    BOOST_REQUIRE(wallet->EncryptWallet("old_pass"));
224
1
    BOOST_REQUIRE(wallet->IsLocked());
225
1
    const auto master_key_record{fail_db->GetRecordValue(DBKeys::MASTER_KEY)};
226
1
    BOOST_REQUIRE(master_key_record);
227
228
1
    fail_db->FailNextWrite(DBKeys::MASTER_KEY); // The injected failure affects only the first attempt
229
1
    const auto changed{wallet->ChangeWalletPassphrase("old_pass", "new_pass")};
230
1
    BOOST_REQUIRE(!changed);
231
1
    BOOST_CHECK_EQUAL(changed.error().code, WalletErrorCode::GenericError);
232
1
    BOOST_CHECK_EQUAL(changed.error().message.original, "Error: Writing the new encryption key to the wallet database failed");
233
1
    BOOST_CHECK( wallet->IsLocked());
234
1
    BOOST_CHECK( fail_db->GetRecordValue(DBKeys::MASTER_KEY) == master_key_record);
235
1
    BOOST_CHECK( wallet->Unlock("old_pass"));
236
1
    wallet->Lock();
237
1
    BOOST_CHECK(!wallet->Unlock("new_pass"));
238
1
    BOOST_CHECK( wallet->ChangeWalletPassphrase("old_pass", "new_pass"));
239
1
    BOOST_CHECK( wallet->IsLocked());
240
1
    BOOST_CHECK( fail_db->GetRecordValue(DBKeys::MASTER_KEY) != master_key_record);
241
1
    BOOST_CHECK( wallet->Unlock("new_pass"));
242
1
    wallet->Lock();
243
1
    const auto unlocked{wallet->Unlock("old_pass")};
244
1
    BOOST_REQUIRE(!unlocked);
245
1
    BOOST_CHECK_EQUAL(unlocked.error().code, WalletErrorCode::PassphraseIncorrect);
246
1
    BOOST_CHECK_EQUAL(unlocked.error().message.original, "Error: The wallet passphrase entered was incorrect.");
247
1
}
248
249
BOOST_FIXTURE_TEST_CASE(add_encrypted_descriptor_key_without_plaintext_record, EncryptionFailureSetup)
250
1
{
251
1
    RecreateWallet(WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_BLANK_WALLET);
252
1
    BOOST_REQUIRE(wallet->EncryptWallet("passphrase"));
253
1
    BOOST_REQUIRE(wallet->Unlock("passphrase"));
254
255
1
    AddKey(*wallet, GenerateRandomKey());
256
1
    BOOST_CHECK( wallet->HaveCryptedKeys());
257
1
    BOOST_CHECK( fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORCKEY));
258
1
    BOOST_CHECK(!fail_db->HasRecordType(DBKeys::WALLETDESCRIPTORKEY));
259
1
}
260
261
BOOST_FIXTURE_TEST_CASE(add_descriptor_key_database_failure, EncryptionFailureSetup)
262
1
{
263
1
    enum class Failure { PlaintextWrite, EncryptedWrite, Erase, Commit };
264
4
    for (auto failure : {Failure::PlaintextWrite, Failure::EncryptedWrite, Failure::Erase, Failure::Commit}) {
265
4
        const bool encrypted{failure != Failure::PlaintextWrite};
266
4
        RecreateWallet(WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_BLANK_WALLET);
267
4
        CKey key{GenerateRandomKey()};
268
        // Add a public descriptor first so the private-key update exercises an existing live manager
269
4
        auto* spkm{CreateDescriptor(*wallet, strprintf("combo(%s)", HexStr(key.GetPubKey())), /*success=*/true)};
270
4
        WalletDescriptor descriptor{WITH_LOCK(spkm->cs_desc_man, return spkm->GetWalletDescriptor())};
271
4
        FlatSigningProvider provider;
272
4
        provider.keys.emplace(key.GetPubKey().GetID(), key);
273
8
        auto add_key{[&] {
274
8
            LOCK(wallet->cs_wallet);
275
8
            return wallet->AddWalletDescriptor(descriptor, provider, /*label=*/"", /*internal=*/false);
276
8
        }};
277
12
        auto has_key{[&] {
278
12
            LOCK(wallet->cs_wallet);
279
12
            return wallet->GetKey(key.GetPubKey().GetID()).has_value();
280
12
        }};
281
4
        if (encrypted) {
282
3
            BOOST_REQUIRE(wallet->EncryptWallet("passphrase"));
283
3
            BOOST_REQUIRE(wallet->Unlock("passphrase"));
284
3
        }
285
4
        BOOST_CHECK(!has_key());
286
287
4
        const std::string record_type{encrypted ? DBKeys::WALLETDESCRIPTORCKEY : DBKeys::WALLETDESCRIPTORKEY};
288
4
        if (failure == Failure::Erase) {
289
1
            fail_db->FailNextErase(DBKeys::WALLETDESCRIPTORKEY);
290
3
        } else if (failure == Failure::Commit) {
291
1
            fail_db->FailNextCommit();
292
2
        } else {
293
2
            fail_db->FailNextWrite(record_type);
294
2
        }
295
4
        BOOST_CHECK_EXCEPTION((void)add_key(), std::runtime_error, HasReason{"UpdateWithSigningProvider: writing descriptor private key failed"});
296
4
        BOOST_CHECK(!has_key());
297
4
        BOOST_CHECK(!fail_db->HasRecordType(record_type));
298
4
        BOOST_CHECK( add_key());
299
4
        BOOST_CHECK( has_key());
300
4
        BOOST_CHECK( fail_db->HasRecordType(record_type));
301
4
    }
302
1
}
303
304
BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
305
1
{
306
1
    CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
307
1
    {
308
1
        LOCK(wallet.cs_wallet);
309
1
        wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
310
1
        auto key{GenerateRandomKey()};
311
1
        auto desc_str{"combo(" + EncodeSecret(key) + ")"};
312
1
        FlatSigningProvider provider;
313
1
        std::string error;
314
1
        auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
315
1
        auto& desc{descs.at(0)};
316
1
        WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
317
1
        BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
318
        // Wallet should update the non-range descriptor successfully
319
1
        BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
320
1
    }
321
1
}
322
323
324
// This test verifies that wallet settings can be added and removed
325
// concurrently, ensuring no race conditions occur during either process.
326
BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
327
1
{
328
1
    auto chain = m_node.chain.get();
329
1
    const auto NUM_WALLETS{5};
330
331
    // Since we're counting the number of wallets, ensure we start without any.
332
1
    BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
333
334
2
    const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
335
2
        std::vector<std::thread> threads;
336
2
        threads.reserve(NUM_WALLETS);
337
12
        for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
338
10
        for (auto& t : threads) t.join();
339
340
2
        auto wallets = chain->getRwSetting("wallet");
341
2
        BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
342
2
    };
wallet_tests.cpp:_ZZN6wallet12wallet_tests34write_wallet_settings_concurrently11test_methodEvENK3$_1clIZNS1_11test_methodEvE3$_0EEDaRKT_i
Line
Count
Source
334
1
    const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
335
1
        std::vector<std::thread> threads;
336
1
        threads.reserve(NUM_WALLETS);
337
6
        for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
338
5
        for (auto& t : threads) t.join();
339
340
1
        auto wallets = chain->getRwSetting("wallet");
341
        BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
342
1
    };
wallet_tests.cpp:_ZZN6wallet12wallet_tests34write_wallet_settings_concurrently11test_methodEvENK3$_1clIZNS1_11test_methodEvE3$_2EEDaRKT_i
Line
Count
Source
334
1
    const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
335
1
        std::vector<std::thread> threads;
336
1
        threads.reserve(NUM_WALLETS);
337
6
        for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
338
5
        for (auto& t : threads) t.join();
339
340
1
        auto wallets = chain->getRwSetting("wallet");
341
        BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
342
1
    };
343
344
    // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
345
5
    check_concurrent_wallet([&chain](int i) {
346
5
        Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
347
5
    },
348
1
                            /*num_expected_wallets=*/NUM_WALLETS);
349
350
    // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
351
5
    check_concurrent_wallet([&chain](int i) {
352
5
        Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
353
5
    },
354
1
                            /*num_expected_wallets=*/0);
355
1
}
356
357
static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
358
6
{
359
6
    CMutableTransaction tx;
360
6
    TxState state = TxStateInactive{};
361
6
    tx.nLockTime = lockTime;
362
6
    FakeNodeClock clock{mock_time};
363
6
    CBlockIndex* block = nullptr;
364
6
    if (blockTime > 0) {
365
5
        LOCK(cs_main);
366
5
        auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
367
5
        assert(inserted.second);
368
5
        const uint256& hash = inserted.first->first;
369
5
        block = &inserted.first->second;
370
5
        block->nTime = blockTime;
371
5
        block->phashBlock = &hash;
372
5
        state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
373
5
    }
374
6
    return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
375
        // Assign wtx.m_state to simplify test and avoid the need to simulate
376
        // reorg events. Without this, AddToWallet asserts false when the same
377
        // transaction is confirmed in different blocks.
378
6
        wtx.m_state = state;
379
6
        return true;
380
6
    })->nTimeSmart;
381
6
}
382
383
// Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
384
// expanded to cover more corner cases of smart time logic.
385
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
386
1
{
387
    // New transaction should use clock time if lower than block time.
388
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100s, 120), 100);
389
390
    // Test that updating existing transaction does not change smart time.
391
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200s, 220), 100);
392
393
    // New transaction should use clock time if there's no block time.
394
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300s, 0), 300);
395
396
    // New transaction should use block time if lower than clock time.
397
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420s, 400), 400);
398
399
    // New transaction should use latest entry time if higher than
400
    // min(block time, clock time).
401
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500s, 390), 400);
402
403
    // If there are future entries, new transaction should use time of the
404
    // newest entry that is no more than 300 seconds ahead of the clock time.
405
1
    BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50s, 600), 300);
406
1
}
407
408
void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
409
3
{
410
3
    node::NodeContext node;
411
3
    auto chain{interfaces::MakeChain(node)};
412
3
    DatabaseOptions options;
413
3
    options.require_format = format;
414
3
    DatabaseStatus status;
415
3
    bilingual_str error;
416
3
    std::vector<bilingual_str> warnings;
417
3
    auto database{MakeWalletDatabase(name, options, status, error)};
418
3
    auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
419
3
    BOOST_CHECK_EQUAL(wallet->PopulateWalletFromDB(error, warnings), DBErrors::LOAD_OK);
420
3
    WITH_LOCK(wallet->cs_wallet, f(wallet));
421
3
}
422
423
BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
424
1
{
425
1
    for (DatabaseFormat format : DATABASE_FORMATS) {
426
1
        const std::string name{strprintf("receive-requests-%i", format)};
427
1
        TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
428
1
            BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
429
1
            WalletBatch batch{wallet->GetDatabase()};
430
1
            BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
431
1
            BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
432
1
            BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
433
1
            BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
434
1
            BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
435
1
            BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
436
1
            BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
437
1
        });
438
1
        TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
439
1
            BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
440
1
            BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
441
1
            auto requests = wallet->GetAddressReceiveRequests();
442
1
            auto erequests = {"val_rr11", "val_rr20"};
443
1
            BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
444
1
            RunWithinTxn(wallet->GetDatabase(), /*process_desc=*/"test", [](WalletBatch& batch){
445
1
                BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
446
1
                BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
447
1
                return true;
448
1
            });
449
1
        });
450
1
        TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
451
1
            BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
452
1
            BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
453
1
            auto requests = wallet->GetAddressReceiveRequests();
454
1
            auto erequests = {"val_rr11"};
455
1
            BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
456
1
        });
457
1
    }
458
1
}
459
460
class ListCoinsTestingSetup : public TestChain100Setup
461
{
462
public:
463
    ListCoinsTestingSetup()
464
2
    {
465
2
        CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
466
2
        wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
467
2
    }
468
469
    ~ListCoinsTestingSetup()
470
2
    {
471
2
        wallet.reset();
472
2
    }
473
474
    CWalletTx& AddTx(CRecipient recipient)
475
5
    {
476
5
        CTransactionRef tx;
477
5
        CCoinControl dummy;
478
5
        {
479
5
            auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
480
5
            BOOST_CHECK(res);
481
5
            tx = res->tx;
482
5
        }
483
5
        wallet->CommitTransaction(tx);
484
5
        CMutableTransaction blocktx;
485
5
        {
486
5
            LOCK(wallet->cs_wallet);
487
5
            blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).GetTx());
488
5
        }
489
5
        CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
490
491
5
        LOCK(wallet->cs_wallet);
492
5
        LOCK(Assert(m_node.chainman)->GetMutex());
493
5
        wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
494
5
        auto it = wallet->mapWallet.find(tx->GetHash());
495
5
        BOOST_CHECK(it != wallet->mapWallet.end());
496
5
        it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
497
5
        return it->second;
498
5
    }
499
500
    std::unique_ptr<CWallet> wallet;
501
};
502
503
BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
504
1
{
505
1
    std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
506
507
    // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
508
    // address.
509
1
    std::map<CTxDestination, std::vector<COutput>> list;
510
1
    {
511
1
        LOCK(wallet->cs_wallet);
512
1
        list = ListCoins(*wallet);
513
1
    }
514
1
    BOOST_CHECK_EQUAL(list.size(), 1U);
515
1
    BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
516
1
    BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
517
518
    // Check initial balance from one mature coinbase transaction.
519
1
    BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
520
521
    // Add a transaction creating a change address, and confirm ListCoins still
522
    // returns the coin associated with the change address underneath the
523
    // coinbaseKey pubkey, even though the change address has a different
524
    // pubkey.
525
1
    AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
526
1
    {
527
1
        LOCK(wallet->cs_wallet);
528
1
        list = ListCoins(*wallet);
529
1
    }
530
1
    BOOST_CHECK_EQUAL(list.size(), 1U);
531
1
    BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
532
1
    BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
533
534
    // Lock both coins. Confirm number of available coins drops to 0.
535
1
    {
536
1
        LOCK(wallet->cs_wallet);
537
1
        BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 2U);
538
1
    }
539
1
    for (const auto& group : list) {
540
2
        for (const auto& coin : group.second) {
541
2
            LOCK(wallet->cs_wallet);
542
2
            wallet->LockCoin(coin.outpoint, /*persist=*/false);
543
2
        }
544
1
    }
545
1
    {
546
1
        LOCK(wallet->cs_wallet);
547
1
        BOOST_CHECK_EQUAL(AvailableCoins(*wallet).Size(), 0U);
548
1
    }
549
    // Confirm ListCoins still returns same result as before, despite coins
550
    // being locked.
551
1
    {
552
1
        LOCK(wallet->cs_wallet);
553
1
        list = ListCoins(*wallet);
554
1
    }
555
1
    BOOST_CHECK_EQUAL(list.size(), 1U);
556
1
    BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
557
1
    BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
558
1
}
559
560
void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
561
                     std::map<OutputType, size_t>& expected_coins_sizes)
562
4
{
563
4
    LOCK(context.wallet->cs_wallet);
564
4
    util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
565
4
    CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
566
4
    CoinFilterParams filter;
567
4
    filter.skip_locked = false;
568
4
    CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
569
    // Lock outputs so they are not spent in follow-up transactions
570
12
    for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}, /*persist=*/false);
571
4
    for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
572
4
}
573
574
BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
575
1
{
576
1
    std::map<OutputType, size_t> expected_coins_sizes;
577
4
    for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
578
579
    // Verify our wallet has one usable coinbase UTXO before starting
580
    // This UTXO is a P2PK, so it should show up in the Other bucket
581
1
    expected_coins_sizes[OutputType::UNKNOWN] = 1U;
582
1
    CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
583
1
    BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
584
1
    BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
585
586
    // We will create a self transfer for each of the OutputTypes and
587
    // verify it is put in the correct bucket after running GetAvailablecoins
588
    //
589
    // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
590
    //   1. One UTXO as the recipient
591
    //   2. One UTXO from the change, due to payment address matching logic
592
593
4
    for (const auto& out_type : OUTPUT_TYPES) {
594
4
        if (out_type == OutputType::UNKNOWN) continue;
595
4
        expected_coins_sizes[out_type] = 2U;
596
4
        TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
597
4
    }
598
1
}
599
600
BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, BasicTestingSetup)
601
1
{
602
1
    const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
603
1
    LOCK(wallet->cs_wallet);
604
1
    wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
605
1
    wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
606
1
    BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
607
1
}
608
609
// Explicit calculation which is used to test the wallet constant
610
// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
611
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
612
2
{
613
    // Generate ephemeral valid pubkey
614
2
    CKey key = GenerateRandomKey();
615
2
    CPubKey pubkey = key.GetPubKey();
616
617
    // Generate pubkey hash
618
2
    uint160 key_hash(Hash160(pubkey));
619
620
    // Create inner-script to enter into keystore. Key hash can't be 0...
621
2
    CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
622
623
    // Create outer P2SH script for the output
624
2
    uint160 script_id(Hash160(inner_script));
625
2
    CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
626
627
    // Add inner-script to key store and key to watchonly
628
2
    FillableSigningProvider keystore;
629
2
    BOOST_CHECK(keystore.AddCScript(inner_script));
630
2
    keystore.AddKeyPubKey(key, pubkey);
631
632
    // Fill in dummy signatures for fee calculation.
633
2
    SignatureData sig_data;
634
635
2
    if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
636
        // We're hand-feeding it correct arguments; shouldn't happen
637
0
        assert(false);
638
0
    }
639
640
2
    CTxIn tx_in;
641
2
    UpdateInput(tx_in, sig_data);
642
2
    return (size_t)GetVirtualTransactionInputSize(tx_in);
643
2
}
644
645
BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, BasicTestingSetup)
646
1
{
647
1
    BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
648
1
    BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
649
1
}
650
651
bool malformed_descriptor(std::ios_base::failure e)
652
1
{
653
1
    std::string s(e.what());
654
1
    return s.find("Missing checksum") != std::string::npos;
655
1
}
656
657
BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
658
1
{
659
1
    std::vector<unsigned char> malformed_record;
660
1
    VectorWriter vw{malformed_record, 0};
661
1
    vw << std::string("notadescriptor");
662
1
    vw << uint64_t{0};
663
1
    vw << int32_t{0};
664
1
    vw << int32_t{0};
665
1
    vw << int32_t{1};
666
667
1
    SpanReader vr{malformed_record};
668
1
    std::optional<WalletDescriptor> w_desc;
669
1
    BOOST_CHECK_EXCEPTION(w_desc.emplace(WalletDescriptor::FromStream(deserialize, vr)), std::ios_base::failure, malformed_descriptor);
670
1
}
671
672
//! Test CWallet::CreateNew() and its behavior handling potential race
673
//! conditions if it's called the same time an incoming transaction shows up in
674
//! the mempool or a new block.
675
//!
676
//! It isn't possible to verify there aren't race condition in every case, so
677
//! this test just checks two specific cases and ensures that timing of
678
//! notifications in these cases doesn't prevent the wallet from detecting
679
//! transactions.
680
//!
681
//! In the first case, block and mempool transactions are created before the
682
//! wallet is loaded, but notifications about these transactions are delayed
683
//! until after it is loaded. The notifications are superfluous in this case, so
684
//! the test verifies the transactions are detected before they arrive.
685
//!
686
//! In the second case, block and mempool transactions are created after the
687
//! wallet rescan and notifications are immediately synced, to verify the wallet
688
//! must already have a handler in place for them, and there's no gap after
689
//! rescanning where new transactions in new blocks could be lost.
690
BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
691
1
{
692
1
    m_args.ForceSetArg("-unsafesqlitesync", "1");
693
    // Create new wallet with known key and unload it.
694
1
    WalletContext context;
695
1
    context.args = &m_args;
696
1
    context.chain = m_node.chain.get();
697
1
    auto wallet = TestCreateWallet(context);
698
1
    CKey key = GenerateRandomKey();
699
1
    AddKey(*wallet, key);
700
1
    TestUnloadWallet(std::move(wallet));
701
702
703
    // Add log hook to detect AddToWallet events from rescans, blockConnected,
704
    // and transactionAddedToMempool notifications
705
1
    int addtx_count = 0;
706
10
    DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
707
10
        if (s) ++addtx_count;
708
10
        return false;
709
10
    });
710
711
712
1
    bool rescan_completed = false;
713
2
    DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
714
2
        if (s) rescan_completed = true;
715
2
        return false;
716
2
    });
717
718
719
    // Block the queue to prevent the wallet receiving blockConnected and
720
    // transactionAddedToMempool notifications, and create block and mempool
721
    // transactions paying to the wallet
722
1
    std::promise<void> promise;
723
1
    m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
724
1
        promise.get_future().wait();
725
1
    });
726
1
    std::string error;
727
1
    m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), /*sync=*/false).vtx[0]);
728
1
    auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
729
1
    m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), /*sync=*/false).vtx[0]);
730
1
    auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
731
1
    BOOST_CHECK(BroadcastTestSimpleSpend(*m_node.chain, *Assert(m_node.chainman), mempool_tx, error));
732
733
    // Reload wallet and make sure new transactions are detected despite events
734
    // being blocked
735
    // Loading will also ask for current mempool transactions
736
1
    wallet = TestLoadWallet(context);
737
1
    BOOST_CHECK(rescan_completed);
738
    // AddToWallet events for block_tx and mempool_tx (x2)
739
1
    BOOST_CHECK_EQUAL(addtx_count, 3);
740
1
    {
741
1
        LOCK(wallet->cs_wallet);
742
1
        BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
743
1
        BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
744
1
    }
745
746
747
    // Unblock notification queue and make sure stale blockConnected and
748
    // transactionAddedToMempool events are processed
749
1
    promise.set_value();
750
1
    m_node.validation_signals->SyncWithValidationInterfaceQueue();
751
    // AddToWallet events for block_tx and mempool_tx events are counted a
752
    // second time as the notification queue is processed
753
1
    BOOST_CHECK_EQUAL(addtx_count, 5);
754
755
756
1
    TestUnloadWallet(std::move(wallet));
757
758
759
    // Load wallet again, this time creating new block and mempool transactions
760
    // paying to the wallet as the wallet finishes loading and syncing the
761
    // queue so the events have to be handled immediately. Releasing the wallet
762
    // lock during the sync is a little artificial but is needed to avoid a
763
    // deadlock during the sync and simulates a new block notification happening
764
    // as soon as possible.
765
1
    addtx_count = 0;
766
1
    auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
767
1
            BOOST_CHECK(rescan_completed);
768
1
            m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
769
1
            block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
770
1
            m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
771
1
            mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
772
1
            BOOST_CHECK(BroadcastTestSimpleSpend(*m_node.chain, *Assert(m_node.chainman), mempool_tx, error));
773
1
            m_node.validation_signals->SyncWithValidationInterfaceQueue();
774
1
        });
775
1
    wallet = TestLoadWallet(context);
776
    // Since mempool transactions are requested at the end of loading, there will
777
    // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
778
1
    BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
779
1
    {
780
1
        LOCK(wallet->cs_wallet);
781
1
        BOOST_CHECK(wallet->mapWallet.contains(block_tx.GetHash()));
782
1
        BOOST_CHECK(wallet->mapWallet.contains(mempool_tx.GetHash()));
783
1
    }
784
785
786
1
    TestUnloadWallet(std::move(wallet));
787
1
}
788
789
BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
790
1
{
791
1
    WalletContext context;
792
1
    context.args = &m_args;
793
1
    auto wallet = TestCreateWallet(context);
794
1
    BOOST_CHECK(wallet);
795
1
    WaitForDeleteWallet(std::move(wallet));
796
1
}
797
798
BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
799
1
{
800
1
    m_args.ForceSetArg("-unsafesqlitesync", "1");
801
1
    WalletContext context;
802
1
    context.args = &m_args;
803
1
    context.chain = m_node.chain.get();
804
1
    auto wallet = TestCreateWallet(context);
805
1
    CKey key = GenerateRandomKey();
806
1
    AddKey(*wallet, key);
807
808
1
    m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
809
1
    auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
810
1
    CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
811
812
1
    m_node.validation_signals->SyncWithValidationInterfaceQueue();
813
814
1
    {
815
1
        auto block_hash = block_tx.GetHash();
816
1
        auto prev_tx = m_coinbase_txns[0];
817
818
1
        LOCK(wallet->cs_wallet);
819
1
        BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
820
1
        BOOST_CHECK(wallet->mapWallet.contains(block_hash));
821
822
1
        std::vector<Txid> vHashIn{ block_hash };
823
1
        BOOST_CHECK(wallet->RemoveTxs(vHashIn));
824
825
1
        BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
826
1
        BOOST_CHECK(!wallet->mapWallet.contains(block_hash));
827
1
    }
828
829
1
    TestUnloadWallet(std::move(wallet));
830
1
}
831
832
BOOST_AUTO_TEST_SUITE_END()
833
} // namespace wallet