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