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