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