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