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