Branch data Line data Source code
1 : : // Copyright (c) 2012-2022 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 <future>
8 : : #include <memory>
9 : : #include <stdint.h>
10 : : #include <vector>
11 : :
12 : : #include <addresstype.h>
13 : : #include <interfaces/chain.h>
14 : : #include <key_io.h>
15 : : #include <node/blockstorage.h>
16 : : #include <policy/policy.h>
17 : : #include <rpc/server.h>
18 : : #include <script/solver.h>
19 : : #include <test/util/logging.h>
20 : : #include <test/util/random.h>
21 : : #include <test/util/setup_common.h>
22 : : #include <util/translation.h>
23 : : #include <validation.h>
24 : : #include <validationinterface.h>
25 : : #include <wallet/coincontrol.h>
26 : : #include <wallet/context.h>
27 : : #include <wallet/receive.h>
28 : : #include <wallet/spend.h>
29 : : #include <wallet/test/util.h>
30 : : #include <wallet/test/wallet_test_fixture.h>
31 : :
32 : : #include <boost/test/unit_test.hpp>
33 : : #include <univalue.h>
34 : :
35 : : using node::MAX_BLOCKFILE_SIZE;
36 : :
37 : : namespace wallet {
38 : :
39 : : // Ensure that fee levels defined in the wallet are at least as high
40 : : // as the default levels for node policy.
41 : : static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
42 : : static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
43 : :
44 : : BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
45 : :
46 : 5 : static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
47 : : {
48 : 5 : CMutableTransaction mtx;
49 [ + - ]: 5 : mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
50 [ + - ]: 15 : mtx.vin.push_back({CTxIn{from.GetHash(), index}});
51 : 5 : FillableSigningProvider keystore;
52 [ + - ]: 5 : keystore.AddKey(key);
53 [ + - ]: 5 : std::map<COutPoint, Coin> coins;
54 [ + - ]: 5 : coins[mtx.vin[0].prevout].out = from.vout[index];
55 [ + - ]: 5 : std::map<int, bilingual_str> input_errors;
56 [ + - + - : 10 : BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
+ - ]
57 : 10 : return mtx;
58 : 5 : }
59 : :
60 : 7 : static void AddKey(CWallet& wallet, const CKey& key)
61 : : {
62 : 7 : LOCK(wallet.cs_wallet);
63 : 7 : FlatSigningProvider provider;
64 [ + - ]: 7 : std::string error;
65 [ + - + - : 21 : auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
+ - ]
66 [ - + ]: 7 : assert(descs.size() == 1);
67 [ + - ]: 7 : auto& desc = descs.at(0);
68 [ + - + - ]: 7 : WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
69 [ + - + - : 7 : auto spk_manager = *Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
+ - ]
70 [ - + ]: 7 : assert(spk_manager);
71 [ + - ]: 14 : }
72 : :
73 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
74 : : {
75 : : // Cap last block file size, and mine new block in a new block file.
76 [ + - + - : 4 : CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
+ - ]
77 [ + - + - ]: 3 : WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
78 [ + - ]: 2 : CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
79 [ + - + - : 4 : CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
+ - ]
80 : :
81 : : // Verify ScanForWalletTransactions fails to read an unknown start block.
82 : 1 : {
83 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
84 : 1 : {
85 [ + - ]: 1 : LOCK(wallet.cs_wallet);
86 [ + - + - ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
87 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
88 [ + - + - : 2 : wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - + - ]
89 [ + - ]: 1 : }
90 [ + - ]: 1 : AddKey(wallet, coinbaseKey);
91 : 1 : WalletRescanReserver reserver(wallet);
92 : 1 : reserver.reserve();
93 [ + - ]: 1 : CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
94 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
95 [ + - + - : 2 : BOOST_CHECK(result.last_failed_block.IsNull());
+ - ]
96 [ + - + - : 2 : BOOST_CHECK(result.last_scanned_block.IsNull());
+ - ]
97 [ + - + - : 2 : BOOST_CHECK(!result.last_scanned_height);
+ - ]
98 [ + - + - : 1 : BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
+ - ]
99 : 1 : }
100 : :
101 : : // Verify ScanForWalletTransactions picks up transactions in both the old
102 : : // and new block files.
103 : 1 : {
104 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
105 : 1 : {
106 [ + - ]: 1 : LOCK(wallet.cs_wallet);
107 [ + - + - ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
108 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
109 [ + - + - : 2 : wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - + - ]
110 [ + - ]: 1 : }
111 [ + - ]: 1 : AddKey(wallet, coinbaseKey);
112 : 1 : WalletRescanReserver reserver(wallet);
113 : 1 : std::chrono::steady_clock::time_point fake_time;
114 : 8 : reserver.setNow([&] { fake_time += 60s; return fake_time; });
115 : 1 : reserver.reserve();
116 : :
117 : 1 : {
118 : 1 : CBlockLocator locator;
119 [ + - + - : 3 : BOOST_CHECK(!WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
+ - + - +
- ]
120 [ + - + - ]: 2 : BOOST_CHECK(locator.IsNull());
121 : 0 : }
122 : :
123 [ + - ]: 1 : CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
124 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
125 [ + - + - : 2 : BOOST_CHECK(result.last_failed_block.IsNull());
+ - ]
126 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
127 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
128 [ + - + - : 1 : BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
+ - ]
129 : :
130 : 1 : {
131 : 1 : CBlockLocator locator;
132 [ + - + - : 3 : BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
+ - + - +
- ]
133 [ + - + - ]: 2 : BOOST_CHECK(!locator.IsNull());
134 : 0 : }
135 : 1 : }
136 : :
137 : : // Prune the older block file.
138 : 1 : int file_number;
139 : 1 : {
140 : 1 : LOCK(cs_main);
141 : 1 : file_number = oldTip->GetBlockPos().nFile;
142 [ + - + - ]: 1 : Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
143 : 0 : }
144 [ + - ]: 1 : m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
145 : :
146 : : // Verify ScanForWalletTransactions only picks transactions in the new block
147 : : // file.
148 : 1 : {
149 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
150 : 1 : {
151 [ + - ]: 1 : LOCK(wallet.cs_wallet);
152 [ + - + - ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
153 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
154 [ + - + - : 2 : wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - + - ]
155 [ + - ]: 1 : }
156 [ + - ]: 1 : AddKey(wallet, coinbaseKey);
157 : 1 : WalletRescanReserver reserver(wallet);
158 : 1 : reserver.reserve();
159 [ + - ]: 1 : CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
160 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
161 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
162 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
163 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
164 [ + - + - : 1 : BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
+ - ]
165 : 1 : }
166 : :
167 : : // Prune the remaining block file.
168 : 1 : {
169 : 1 : LOCK(cs_main);
170 : 1 : file_number = newTip->GetBlockPos().nFile;
171 [ + - + - ]: 1 : Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
172 : 0 : }
173 [ + - ]: 1 : m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
174 : :
175 : : // Verify ScanForWalletTransactions scans no blocks.
176 : 1 : {
177 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
178 : 1 : {
179 [ + - ]: 1 : LOCK(wallet.cs_wallet);
180 [ + - + - ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
181 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
182 [ + - + - : 2 : wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - + - ]
183 [ + - ]: 1 : }
184 [ + - ]: 1 : AddKey(wallet, coinbaseKey);
185 : 1 : WalletRescanReserver reserver(wallet);
186 : 1 : reserver.reserve();
187 [ + - ]: 1 : CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
188 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
189 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
190 [ + - + - : 2 : BOOST_CHECK(result.last_scanned_block.IsNull());
+ - ]
191 [ + - + - : 2 : BOOST_CHECK(!result.last_scanned_height);
+ - ]
192 [ + - + - : 1 : BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
+ - ]
193 : 1 : }
194 : 1 : }
195 : :
196 : : // This test verifies that wallet settings can be added and removed
197 : : // concurrently, ensuring no race conditions occur during either process.
198 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
199 : : {
200 : 1 : auto chain = m_node.chain.get();
201 : 1 : const auto NUM_WALLETS{5};
202 : :
203 : : // Since we're counting the number of wallets, ensure we start without any.
204 [ + - + - : 2 : BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
+ - ]
205 : :
206 : 3 : const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
207 : 2 : std::vector<std::thread> threads;
208 [ + - ]: 2 : threads.reserve(NUM_WALLETS);
209 [ + - + + ]: 12 : for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
210 [ + - + + ]: 12 : for (auto& t : threads) t.join();
211 : :
212 [ + - + - ]: 2 : auto wallets = chain->getRwSetting("wallet");
213 [ + - + - : 2 : BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
+ - ]
214 : 3 : };
215 : :
216 : : // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
217 : 6 : check_concurrent_wallet([&chain](int i) {
218 [ + - + - ]: 5 : Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
219 : 5 : },
220 : : /*num_expected_wallets=*/NUM_WALLETS);
221 : :
222 : : // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
223 : 6 : check_concurrent_wallet([&chain](int i) {
224 [ + - + - ]: 5 : Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
225 : 5 : },
226 : : /*num_expected_wallets=*/0);
227 : 1 : }
228 : :
229 : : // Check that GetImmatureCredit() returns a newly calculated value instead of
230 : : // the cached value after a MarkDirty() call.
231 : : //
232 : : // This is a regression test written to verify a bugfix for the immature credit
233 : : // function. Similar tests probably should be written for the other credit and
234 : : // debit functions.
235 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
236 : : {
237 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
238 : :
239 [ + - ]: 1 : LOCK(wallet.cs_wallet);
240 [ + - + - ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
241 [ + - + - : 3 : CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
+ - + - -
+ ]
242 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
243 [ + - ]: 1 : wallet.SetupDescriptorScriptPubKeyMans();
244 : :
245 [ + - + - : 2 : wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - + - ]
246 : :
247 : : // Call GetImmatureCredit() once before adding the key to the wallet to
248 : : // cache the current immature credit amount, which is 0.
249 [ + - + - : 1 : BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 0);
+ - ]
250 : :
251 : : // Invalidate the cached value, add the key, and make sure a new immature
252 : : // credit amount is calculated.
253 [ + - ]: 1 : wtx.MarkDirty();
254 [ + - ]: 1 : AddKey(wallet, coinbaseKey);
255 [ + - + - : 1 : BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 50*COIN);
+ - ]
256 [ + - + - ]: 3 : }
257 : :
258 : 6 : static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
259 : : {
260 : 6 : CMutableTransaction tx;
261 [ + - ]: 6 : TxState state = TxStateInactive{};
262 : 6 : tx.nLockTime = lockTime;
263 [ + - ]: 6 : SetMockTime(mockTime);
264 : 6 : CBlockIndex* block = nullptr;
265 [ + + ]: 6 : if (blockTime > 0) {
266 [ + - ]: 5 : LOCK(cs_main);
267 [ + - ]: 5 : auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
268 [ - + ]: 5 : assert(inserted.second);
269 : 5 : const uint256& hash = inserted.first->first;
270 : 5 : block = &inserted.first->second;
271 : 5 : block->nTime = blockTime;
272 : 5 : block->phashBlock = &hash;
273 [ + - ]: 5 : state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
274 : 5 : }
275 [ + - + - ]: 18 : return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
276 : : // Assign wtx.m_state to simplify test and avoid the need to simulate
277 : : // reorg events. Without this, AddToWallet asserts false when the same
278 : : // transaction is confirmed in different blocks.
279 : 6 : wtx.m_state = state;
280 : 6 : return true;
281 [ + - ]: 6 : })->nTimeSmart;
282 : 6 : }
283 : :
284 : : // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
285 : : // expanded to cover more corner cases of smart time logic.
286 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
287 : : {
288 : : // New transaction should use clock time if lower than block time.
289 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
290 : :
291 : : // Test that updating existing transaction does not change smart time.
292 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
293 : :
294 : : // New transaction should use clock time if there's no block time.
295 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
296 : :
297 : : // New transaction should use block time if lower than clock time.
298 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
299 : :
300 : : // New transaction should use latest entry time if higher than
301 : : // min(block time, clock time).
302 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
303 : :
304 : : // If there are future entries, new transaction should use time of the
305 : : // newest entry that is no more than 300 seconds ahead of the clock time.
306 [ + - ]: 1 : BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
307 : 1 : }
308 : :
309 : 3 : void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
310 : : {
311 : 3 : node::NodeContext node;
312 [ + - ]: 3 : auto chain{interfaces::MakeChain(node)};
313 [ + - ]: 3 : DatabaseOptions options;
314 [ + - ]: 3 : options.require_format = format;
315 : 3 : DatabaseStatus status;
316 [ + - ]: 3 : bilingual_str error;
317 : 3 : std::vector<bilingual_str> warnings;
318 [ + - ]: 3 : auto database{MakeWalletDatabase(name, options, status, error)};
319 [ + - ]: 3 : auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
320 [ + - + - : 3 : BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
+ - ]
321 [ + - + - : 15 : WITH_LOCK(wallet->cs_wallet, f(wallet));
+ - + - ]
322 : 6 : }
323 : :
324 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
325 : : {
326 [ + + ]: 2 : for (DatabaseFormat format : DATABASE_FORMATS) {
327 : 1 : const std::string name{strprintf("receive-requests-%i", format)};
328 [ + - ]: 2 : TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
329 [ + - + - ]: 2 : BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
330 : 1 : WalletBatch batch{wallet->GetDatabase()};
331 [ + - + - : 2 : BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
+ - + - ]
332 [ + - + - : 2 : BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
+ - + - ]
333 [ + - + - : 2 : BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
+ - + - +
- + - ]
334 [ + - + - : 2 : BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
+ - + - +
- ]
335 [ + - + - : 2 : BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
+ - + - +
- + - ]
336 [ + - + - : 2 : BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
+ - + - +
- + - ]
337 [ + - + - : 2 : BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
+ - + - +
- ]
338 : 1 : });
339 [ + - ]: 2 : TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
340 [ + - + - ]: 2 : BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
341 [ + - + - ]: 2 : BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
342 : 1 : auto requests = wallet->GetAddressReceiveRequests();
343 : 1 : auto erequests = {"val_rr11", "val_rr20"};
344 [ + - + - : 2 : BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
+ - ]
345 [ + - ]: 1 : RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
346 [ + - + - ]: 2 : BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
347 [ + - + - ]: 2 : BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
348 : 1 : return true;
349 : : });
350 : 1 : });
351 [ + - ]: 3 : TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
352 [ + - + - ]: 2 : BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
353 [ + - + - ]: 2 : BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
354 : 1 : auto requests = wallet->GetAddressReceiveRequests();
355 : 1 : auto erequests = {"val_rr11"};
356 [ + - + - : 2 : BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
+ - ]
357 : 1 : });
358 : 1 : }
359 : 1 : }
360 : :
361 : : class ListCoinsTestingSetup : public TestChain100Setup
362 : : {
363 : : public:
364 : 2 : ListCoinsTestingSetup()
365 [ + - ]: 2 : {
366 [ + - + - : 4 : CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
+ - ]
367 [ + - + - : 6 : wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
+ - - + -
+ + - +
- ]
368 [ + - - - ]: 4 : }
369 : :
370 : 2 : ~ListCoinsTestingSetup()
371 : : {
372 [ + - ]: 2 : wallet.reset();
373 [ - + ]: 2 : }
374 : :
375 : 5 : CWalletTx& AddTx(CRecipient recipient)
376 : : {
377 : 5 : CTransactionRef tx;
378 [ + - ]: 5 : CCoinControl dummy;
379 : 5 : {
380 [ + - + - : 15 : auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
+ + - - ]
381 [ + - + - ]: 10 : BOOST_CHECK(res);
382 : 5 : tx = res->tx;
383 : 0 : }
384 [ + - + - ]: 15 : wallet->CommitTransaction(tx, {}, {});
385 [ + - ]: 5 : CMutableTransaction blocktx;
386 : 5 : {
387 [ + - ]: 5 : LOCK(wallet->cs_wallet);
388 [ + - + - : 10 : blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
+ - ]
389 : 0 : }
390 [ + - + - : 20 : CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
+ - + - +
+ - - ]
391 : :
392 [ + - ]: 5 : LOCK(wallet->cs_wallet);
393 [ + - + - ]: 5 : LOCK(Assert(m_node.chainman)->GetMutex());
394 [ + - + - : 10 : wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
+ - ]
395 [ + - ]: 5 : auto it = wallet->mapWallet.find(tx->GetHash());
396 [ + - + - : 15 : BOOST_CHECK(it != wallet->mapWallet.end());
+ - + - ]
397 [ + - + - : 10 : it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
+ - ]
398 [ + - ]: 5 : return it->second;
399 [ + - + - : 30 : }
+ - + - +
- ]
400 : :
401 : : std::unique_ptr<CWallet> wallet;
402 : : };
403 : :
404 [ + - + - : 10 : BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
405 : : {
406 : 1 : std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
407 : :
408 : : // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
409 : : // address.
410 [ + - ]: 1 : std::map<CTxDestination, std::vector<COutput>> list;
411 : 1 : {
412 [ + - ]: 1 : LOCK(wallet->cs_wallet);
413 [ + - + - ]: 2 : list = ListCoins(*wallet);
414 : 0 : }
415 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.size(), 1U);
416 [ + - - + : 1 : BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
+ - + - ]
417 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
418 : :
419 : : // Check initial balance from one mature coinbase transaction.
420 [ + - + - : 3 : BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
+ - ]
421 : :
422 : : // Add a transaction creating a change address, and confirm ListCoins still
423 : : // returns the coin associated with the change address underneath the
424 : : // coinbaseKey pubkey, even though the change address has a different
425 : : // pubkey.
426 [ + - ]: 1 : AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
427 : 1 : {
428 [ + - ]: 1 : LOCK(wallet->cs_wallet);
429 [ + - + - ]: 2 : list = ListCoins(*wallet);
430 : 0 : }
431 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.size(), 1U);
432 [ + - - + : 1 : BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
+ - + - ]
433 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
434 : :
435 : : // Lock both coins. Confirm number of available coins drops to 0.
436 : 1 : {
437 [ + - ]: 1 : LOCK(wallet->cs_wallet);
438 [ + - + - : 1 : BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 2U);
+ - + - +
- ]
439 : 0 : }
440 [ + + ]: 2 : for (const auto& group : list) {
441 [ + + ]: 3 : for (const auto& coin : group.second) {
442 [ + - ]: 2 : LOCK(wallet->cs_wallet);
443 [ + - ]: 2 : wallet->LockCoin(coin.outpoint);
444 : 2 : }
445 : : }
446 : 1 : {
447 [ + - ]: 1 : LOCK(wallet->cs_wallet);
448 [ + - + - : 1 : BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 0U);
+ - + - +
- ]
449 : 0 : }
450 : : // Confirm ListCoins still returns same result as before, despite coins
451 : : // being locked.
452 : 1 : {
453 [ + - ]: 1 : LOCK(wallet->cs_wallet);
454 [ + - + - ]: 2 : list = ListCoins(*wallet);
455 : 0 : }
456 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.size(), 1U);
457 [ + - - + : 1 : BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
+ - + - ]
458 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
459 : 1 : }
460 : :
461 : 4 : void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
462 : : std::map<OutputType, size_t>& expected_coins_sizes)
463 : : {
464 : 4 : LOCK(context.wallet->cs_wallet);
465 [ + - + - : 4 : util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
+ - ]
466 [ + - + - ]: 8 : CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
467 : 4 : CoinFilterParams filter;
468 : 4 : filter.skip_locked = false;
469 [ + - ]: 4 : CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
470 : : // Lock outputs so they are not spent in follow-up transactions
471 [ + - + + ]: 12 : for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
472 [ + - + - : 24 : for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
+ - + + ]
473 [ + - ]: 8 : }
474 : :
475 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
476 : : {
477 : 1 : std::map<OutputType, size_t> expected_coins_sizes;
478 [ + - + + ]: 5 : for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
479 : :
480 : : // Verify our wallet has one usable coinbase UTXO before starting
481 : : // This UTXO is a P2PK, so it should show up in the Other bucket
482 [ + - ]: 1 : expected_coins_sizes[OutputType::UNKNOWN] = 1U;
483 [ + - ]: 3 : CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
484 [ + - + - : 1 : BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
+ - + - ]
485 [ + - + - : 1 : BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
+ - + - ]
486 : :
487 : : // We will create a self transfer for each of the OutputTypes and
488 : : // verify it is put in the correct bucket after running GetAvailablecoins
489 : : //
490 : : // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
491 : : // 1. One UTXO as the recipient
492 : : // 2. One UTXO from the change, due to payment address matching logic
493 : :
494 [ + + ]: 5 : for (const auto& out_type : OUTPUT_TYPES) {
495 [ - + ]: 4 : if (out_type == OutputType::UNKNOWN) continue;
496 [ + - ]: 4 : expected_coins_sizes[out_type] = 2U;
497 [ + - ]: 4 : TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
498 : : }
499 : 1 : }
500 : :
501 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
502 : : {
503 [ + - + - ]: 1 : const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
504 [ + - ]: 1 : LOCK(wallet->cs_wallet);
505 [ + - ]: 1 : wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
506 [ + - ]: 1 : wallet->SetMinVersion(FEATURE_LATEST);
507 [ + - ]: 1 : wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
508 [ + - + - : 2 : BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
+ - + - +
- ]
509 [ + - ]: 2 : }
510 : :
511 : : // Explicit calculation which is used to test the wallet constant
512 : : // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
513 : 2 : static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
514 : : {
515 : : // Generate ephemeral valid pubkey
516 : 2 : CKey key = GenerateRandomKey();
517 [ + - ]: 2 : CPubKey pubkey = key.GetPubKey();
518 : :
519 : : // Generate pubkey hash
520 [ + - ]: 2 : uint160 key_hash(Hash160(pubkey));
521 : :
522 : : // Create inner-script to enter into keystore. Key hash can't be 0...
523 [ + - + - ]: 2 : CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
524 : :
525 : : // Create outer P2SH script for the output
526 [ + - ]: 2 : uint160 script_id(Hash160(inner_script));
527 [ + - + - : 2 : CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
+ - ]
528 : :
529 : : // Add inner-script to key store and key to watchonly
530 : 2 : FillableSigningProvider keystore;
531 [ + - ]: 2 : keystore.AddCScript(inner_script);
532 [ + - ]: 2 : keystore.AddKeyPubKey(key, pubkey);
533 : :
534 : : // Fill in dummy signatures for fee calculation.
535 : 2 : SignatureData sig_data;
536 : :
537 [ + + + - : 2 : if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
- + ]
538 : : // We're hand-feeding it correct arguments; shouldn't happen
539 : 0 : assert(false);
540 : : }
541 : :
542 : 2 : CTxIn tx_in;
543 [ + - ]: 2 : UpdateInput(tx_in, sig_data);
544 [ + - ]: 2 : return (size_t)GetVirtualTransactionInputSize(tx_in);
545 : 2 : }
546 : :
547 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
548 : : {
549 [ + - ]: 1 : BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
550 [ + - ]: 1 : BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
551 : 1 : }
552 : :
553 : 1 : bool malformed_descriptor(std::ios_base::failure e)
554 : : {
555 : 1 : std::string s(e.what());
556 : 1 : return s.find("Missing checksum") != std::string::npos;
557 : 1 : }
558 : :
559 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
560 : : {
561 : 1 : std::vector<unsigned char> malformed_record;
562 [ + - ]: 1 : VectorWriter vw{malformed_record, 0};
563 [ + - ]: 2 : vw << std::string("notadescriptor");
564 [ + - ]: 1 : vw << uint64_t{0};
565 [ + - ]: 1 : vw << int32_t{0};
566 [ + - ]: 1 : vw << int32_t{0};
567 [ + - ]: 1 : vw << int32_t{1};
568 : :
569 : 1 : SpanReader vr{malformed_record};
570 : 1 : WalletDescriptor w_desc;
571 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
- - - - -
+ + - + -
+ - ]
572 : 1 : }
573 : :
574 : : //! Test CWallet::Create() and its behavior handling potential race
575 : : //! conditions if it's called the same time an incoming transaction shows up in
576 : : //! the mempool or a new block.
577 : : //!
578 : : //! It isn't possible to verify there aren't race condition in every case, so
579 : : //! this test just checks two specific cases and ensures that timing of
580 : : //! notifications in these cases doesn't prevent the wallet from detecting
581 : : //! transactions.
582 : : //!
583 : : //! In the first case, block and mempool transactions are created before the
584 : : //! wallet is loaded, but notifications about these transactions are delayed
585 : : //! until after it is loaded. The notifications are superfluous in this case, so
586 : : //! the test verifies the transactions are detected before they arrive.
587 : : //!
588 : : //! In the second case, block and mempool transactions are created after the
589 : : //! wallet rescan and notifications are immediately synced, to verify the wallet
590 : : //! must already have a handler in place for them, and there's no gap after
591 : : //! rescanning where new transactions in new blocks could be lost.
592 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
593 : : {
594 [ + - + - ]: 2 : m_args.ForceSetArg("-unsafesqlitesync", "1");
595 : : // Create new wallet with known key and unload it.
596 : 1 : WalletContext context;
597 : 1 : context.args = &m_args;
598 [ + - ]: 1 : context.chain = m_node.chain.get();
599 [ + - ]: 1 : auto wallet = TestLoadWallet(context);
600 : 1 : CKey key = GenerateRandomKey();
601 [ + - ]: 1 : AddKey(*wallet, key);
602 [ + - ]: 1 : TestUnloadWallet(std::move(wallet));
603 : :
604 : :
605 : : // Add log hook to detect AddToWallet events from rescans, blockConnected,
606 : : // and transactionAddedToMempool notifications
607 : 1 : int addtx_count = 0;
608 [ + - ]: 11 : DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
609 [ + + ]: 10 : if (s) ++addtx_count;
610 : 10 : return false;
611 [ + - + - ]: 2 : });
612 : :
613 : :
614 : 1 : bool rescan_completed = false;
615 [ + - ]: 3 : DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
616 [ + + ]: 2 : if (s) rescan_completed = true;
617 : 2 : return false;
618 [ + - + - ]: 2 : });
619 : :
620 : :
621 : : // Block the queue to prevent the wallet receiving blockConnected and
622 : : // transactionAddedToMempool notifications, and create block and mempool
623 : : // transactions paying to the wallet
624 [ + - ]: 1 : std::promise<void> promise;
625 [ + - ]: 2 : m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
626 [ + - ]: 1 : promise.get_future().wait();
627 : 1 : });
628 [ + - ]: 1 : std::string error;
629 [ + - + - : 2 : m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
+ - + - ]
630 [ + - + - : 1 : auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
+ - ]
631 [ + - + - : 4 : m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
+ - + - +
- + + -
- ]
632 [ + - + - : 1 : auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
+ - ]
633 [ + - + - : 4 : BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
+ - + - +
- + - ]
634 : :
635 : :
636 : : // Reload wallet and make sure new transactions are detected despite events
637 : : // being blocked
638 : : // Loading will also ask for current mempool transactions
639 [ + - - + ]: 2 : wallet = TestLoadWallet(context);
640 [ + - + - : 2 : BOOST_CHECK(rescan_completed);
+ - ]
641 : : // AddToWallet events for block_tx and mempool_tx (x2)
642 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(addtx_count, 3);
643 : 1 : {
644 [ + - ]: 1 : LOCK(wallet->cs_wallet);
645 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
+ - + - ]
646 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
+ - + - +
- ]
647 : 0 : }
648 : :
649 : :
650 : : // Unblock notification queue and make sure stale blockConnected and
651 : : // transactionAddedToMempool events are processed
652 [ + - ]: 1 : promise.set_value();
653 [ + - ]: 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
654 : : // AddToWallet events for block_tx and mempool_tx events are counted a
655 : : // second time as the notification queue is processed
656 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(addtx_count, 5);
657 : :
658 : :
659 [ + - ]: 1 : TestUnloadWallet(std::move(wallet));
660 : :
661 : :
662 : : // Load wallet again, this time creating new block and mempool transactions
663 : : // paying to the wallet as the wallet finishes loading and syncing the
664 : : // queue so the events have to be handled immediately. Releasing the wallet
665 : : // lock during the sync is a little artificial but is needed to avoid a
666 : : // deadlock during the sync and simulates a new block notification happening
667 : : // as soon as possible.
668 : 1 : addtx_count = 0;
669 [ + - ]: 2 : auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
670 [ + - ]: 2 : BOOST_CHECK(rescan_completed);
671 [ + - + - ]: 2 : m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
672 [ + - ]: 2 : block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
673 [ + - + - : 4 : m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
+ - + + -
- ]
674 [ + - ]: 2 : mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
675 [ + - + - : 4 : BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
+ - + - ]
676 : 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
677 [ + - ]: 3 : });
678 [ + - - + ]: 2 : wallet = TestLoadWallet(context);
679 : : // Since mempool transactions are requested at the end of loading, there will
680 : : // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
681 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
682 : 1 : {
683 [ + - ]: 1 : LOCK(wallet->cs_wallet);
684 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
+ - + - ]
685 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
+ - + - +
- ]
686 : 0 : }
687 : :
688 : :
689 [ + - ]: 1 : TestUnloadWallet(std::move(wallet));
690 [ + - - + ]: 4 : }
691 : :
692 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
693 : : {
694 : 1 : WalletContext context;
695 : 1 : context.args = &m_args;
696 [ + - ]: 1 : auto wallet = TestLoadWallet(context);
697 [ + - + - : 2 : BOOST_CHECK(wallet);
+ - ]
698 [ + - ]: 1 : WaitForDeleteWallet(std::move(wallet));
699 : 1 : }
700 : :
701 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
702 : : {
703 [ + - + - ]: 2 : m_args.ForceSetArg("-unsafesqlitesync", "1");
704 : 1 : WalletContext context;
705 : 1 : context.args = &m_args;
706 [ + - ]: 1 : context.chain = m_node.chain.get();
707 [ + - ]: 1 : auto wallet = TestLoadWallet(context);
708 : 1 : CKey key = GenerateRandomKey();
709 [ + - ]: 1 : AddKey(*wallet, key);
710 : :
711 [ + - ]: 1 : std::string error;
712 [ + - + - : 2 : m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
+ - + - ]
713 [ + - + - : 1 : auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
+ - ]
714 [ + - + - : 4 : CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
+ - + - +
+ - - ]
715 : :
716 [ + - ]: 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
717 : :
718 : 1 : {
719 [ + - ]: 1 : auto block_hash = block_tx.GetHash();
720 [ + - ]: 1 : auto prev_tx = m_coinbase_txns[0];
721 : :
722 [ + - ]: 1 : LOCK(wallet->cs_wallet);
723 [ + - + - : 2 : BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
+ - + - ]
724 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
+ - ]
725 : :
726 [ + - ]: 1 : std::vector<uint256> vHashIn{ block_hash };
727 [ + - + - : 2 : BOOST_CHECK(wallet->RemoveTxs(vHashIn));
+ - + - ]
728 : :
729 [ + - + - : 2 : BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
+ - + - ]
730 [ + - + - : 1 : BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
+ - ]
731 [ + - + - ]: 2 : }
732 : :
733 [ + - ]: 1 : TestUnloadWallet(std::move(wallet));
734 [ + - - + ]: 2 : }
735 : :
736 : : /**
737 : : * Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marked dirty,
738 : : * while the transaction that spends them exist inside the in-memory wallet tx map (not stored on db due a db write failure).
739 : : */
740 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
741 : : {
742 [ + - + - : 2 : CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ - ]
743 : 1 : {
744 [ + - ]: 1 : LOCK(wallet.cs_wallet);
745 [ + - ]: 1 : wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
746 [ + - ]: 1 : wallet.SetupDescriptorScriptPubKeyMans();
747 : 0 : }
748 : :
749 : : // Add tx to wallet
750 [ + - + - : 2 : const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
+ - + - ]
751 : :
752 [ + - ]: 1 : CMutableTransaction mtx;
753 [ + - + - ]: 1 : mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
754 [ + - ]: 1 : mtx.vin.emplace_back(Txid::FromUint256(m_rng.rand256()), 0);
755 [ + - + - : 3 : const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
+ - ]
756 : :
757 : 1 : {
758 : : // Cache and verify available balance for the wtx
759 [ + - ]: 1 : LOCK(wallet.cs_wallet);
760 [ + - ]: 1 : const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
761 [ + - + - : 1 : BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 1 * COIN);
+ - + - ]
762 : 0 : }
763 : :
764 : : // Now the good case:
765 : : // 1) Add a transaction that spends the previously created transaction
766 : : // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
767 : :
768 : 1 : mtx.vin.clear();
769 [ + - ]: 1 : mtx.vin.emplace_back(tx_id_to_spend, 0);
770 [ + - + - ]: 2 : wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
771 [ + - ]: 1 : const auto good_tx_id{mtx.GetHash()};
772 : :
773 : 1 : {
774 : : // Verify balance update for the new tx and the old one
775 [ + - ]: 1 : LOCK(wallet.cs_wallet);
776 [ + - ]: 1 : const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id.ToUint256());
777 [ + - + - : 1 : BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *new_wtx), 1 * COIN);
+ - ]
778 : :
779 : : // Now the old wtx
780 [ + - ]: 1 : const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
781 [ + - + - : 1 : BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 0 * COIN);
+ - + - ]
782 : 0 : }
783 : :
784 : : // Now the bad case:
785 : : // 1) Make db always fail
786 : : // 2) Try to add a transaction that spends the previously created transaction and
787 : : // verify that we are not moving forward if the wallet cannot store it
788 [ + - ]: 1 : GetMockableDatabase(wallet).m_pass = false;
789 : 1 : mtx.vin.clear();
790 [ + - ]: 1 : mtx.vin.emplace_back(good_tx_id, 0);
791 [ + - + - : 4 : BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
- + - - -
- - + + -
+ - + - ]
792 : : std::runtime_error,
793 : : HasReason("DB error adding transaction to wallet, write failed"));
794 : 1 : }
795 : :
796 : : BOOST_AUTO_TEST_SUITE_END()
797 : : } // namespace wallet
|