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