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 <bitcoin-build-config.h>
7 : :
8 : : #include <wallet/wallet.h>
9 : :
10 : : #include <addresstype.h>
11 : : #include <blockfilter.h>
12 : : #include <chain.h>
13 : : #include <coins.h>
14 : : #include <common/args.h>
15 : : #include <common/messages.h>
16 : : #include <common/settings.h>
17 : : #include <common/signmessage.h>
18 : : #include <common/system.h>
19 : : #include <consensus/amount.h>
20 : : #include <consensus/consensus.h>
21 : : #include <consensus/validation.h>
22 : : #include <external_signer.h>
23 : : #include <interfaces/chain.h>
24 : : #include <interfaces/handler.h>
25 : : #include <interfaces/wallet.h>
26 : : #include <kernel/mempool_removal_reason.h>
27 : : #include <kernel/types.h>
28 : : #include <key.h>
29 : : #include <key_io.h>
30 : : #include <node/types.h>
31 : : #include <outputtype.h>
32 : : #include <policy/feerate.h>
33 : : #include <policy/truc_policy.h>
34 : : #include <primitives/block.h>
35 : : #include <primitives/transaction.h>
36 : : #include <psbt.h>
37 : : #include <pubkey.h>
38 : : #include <random.h>
39 : : #include <script/descriptor.h>
40 : : #include <script/interpreter.h>
41 : : #include <script/script.h>
42 : : #include <script/sign.h>
43 : : #include <script/signingprovider.h>
44 : : #include <script/solver.h>
45 : : #include <serialize.h>
46 : : #include <span.h>
47 : : #include <streams.h>
48 : : #include <support/allocators/secure.h>
49 : : #include <support/allocators/zeroafterfree.h>
50 : : #include <support/cleanse.h>
51 : : #include <sync.h>
52 : : #include <tinyformat.h>
53 : : #include <uint256.h>
54 : : #include <univalue.h>
55 : : #include <util/check.h>
56 : : #include <util/expected.h>
57 : : #include <util/fs.h>
58 : : #include <util/fs_helpers.h>
59 : : #include <util/log.h>
60 : : #include <util/moneystr.h>
61 : : #include <util/result.h>
62 : : #include <util/string.h>
63 : : #include <util/time.h>
64 : : #include <util/translation.h>
65 : : #include <wallet/coincontrol.h>
66 : : #include <wallet/context.h>
67 : : #include <wallet/crypter.h>
68 : : #include <wallet/db.h>
69 : : #include <wallet/external_signer_scriptpubkeyman.h>
70 : : #include <wallet/scan.h>
71 : : #include <wallet/scriptpubkeyman.h>
72 : : #include <wallet/transaction.h>
73 : : #include <wallet/types.h>
74 : : #include <wallet/walletdb.h>
75 : : #include <wallet/walletutil.h>
76 : :
77 : : #include <algorithm>
78 : : #include <condition_variable>
79 : : #include <exception>
80 : : #include <limits>
81 : : #include <optional>
82 : : #include <stdexcept>
83 : : #include <thread>
84 : : #include <tuple>
85 : : #include <utility>
86 : : #include <variant>
87 : :
88 : : struct KeyOriginInfo;
89 : :
90 : : using common::AmountErrMsg;
91 : : using common::AmountHighWarn;
92 : : using common::PSBTError;
93 : : using interfaces::FoundBlock;
94 : : using kernel::ChainstateRole;
95 : : using util::ReplaceAll;
96 : : using util::ToString;
97 : :
98 : : namespace wallet {
99 : :
100 : : /**
101 : : * Refresh mempool status so the wallet is in an internally consistent state and
102 : : * immediately knows the transaction's status: Whether it can be considered
103 : : * trusted and is eligible to be abandoned ...
104 : : */
105 : 0 : static void RefreshMempoolStatus(CWalletTx& tx, interfaces::Chain& chain)
106 : : {
107 [ # # ]: 0 : if (chain.isInMempool(tx.GetHash())) {
108 [ # # ]: 0 : tx.m_state = TxStateInMempool();
109 [ # # ]: 0 : } else if (tx.state<TxStateInMempool>()) {
110 [ # # ]: 0 : tx.m_state = TxStateInactive();
111 : : }
112 : 0 : }
113 : :
114 : 0 : bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
115 : : {
116 : 0 : LOCK(context.wallets_mutex);
117 [ # # ]: 0 : assert(wallet);
118 [ # # ]: 0 : std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
119 [ # # ]: 0 : if (i != context.wallets.end()) return false;
120 [ # # ]: 0 : context.wallets.push_back(wallet);
121 [ # # ]: 0 : wallet->ConnectScriptPubKeyManNotifiers();
122 [ # # ]: 0 : wallet->NotifyCanGetAddressesChanged();
123 : : return true;
124 : 0 : }
125 : :
126 : 0 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
127 : : {
128 [ # # ]: 0 : assert(wallet);
129 : :
130 : 0 : interfaces::Chain& chain = wallet->chain();
131 [ # # ]: 0 : std::string name = wallet->GetName();
132 [ # # # # ]: 0 : WITH_LOCK(wallet->cs_wallet, wallet->WriteBestBlock());
133 : :
134 : : // Unregister with the validation interface which also drops shared pointers.
135 [ # # ]: 0 : wallet->DisconnectChainNotifications();
136 : 0 : {
137 [ # # ]: 0 : LOCK(context.wallets_mutex);
138 : 0 : std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
139 [ # # # # ]: 0 : if (i == context.wallets.end()) return false;
140 [ # # ]: 0 : context.wallets.erase(i);
141 : 0 : }
142 : : // Notify unload so that upper layers release the shared pointer.
143 [ # # ]: 0 : wallet->NotifyUnload();
144 : :
145 : : // Write the wallet setting
146 [ # # ]: 0 : UpdateWalletSetting(chain, name, load_on_start, warnings);
147 : :
148 : : return true;
149 : 0 : }
150 : :
151 : 0 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
152 : : {
153 : 0 : std::vector<bilingual_str> warnings;
154 [ # # ]: 0 : return RemoveWallet(context, wallet, load_on_start, warnings);
155 : 0 : }
156 : :
157 : 0 : std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context)
158 : : {
159 : 0 : LOCK(context.wallets_mutex);
160 [ # # ]: 0 : return context.wallets;
161 : 0 : }
162 : :
163 : 0 : std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count)
164 : : {
165 : 0 : LOCK(context.wallets_mutex);
166 [ # # ]: 0 : count = context.wallets.size();
167 [ # # # # : 0 : return count == 1 ? context.wallets[0] : nullptr;
# # ]
168 : 0 : }
169 : :
170 : 0 : std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name)
171 : : {
172 : 0 : LOCK(context.wallets_mutex);
173 [ # # ]: 0 : for (const std::shared_ptr<CWallet>& wallet : context.wallets) {
174 [ # # # # : 0 : if (wallet->GetName() == name) return wallet;
# # ]
175 : : }
176 : 0 : return nullptr;
177 : 0 : }
178 : :
179 : 0 : std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet)
180 : : {
181 : 0 : LOCK(context.wallets_mutex);
182 [ # # ]: 0 : auto it = context.wallet_load_fns.emplace(context.wallet_load_fns.end(), std::move(load_wallet));
183 [ # # # # : 0 : return interfaces::MakeCleanupHandler([&context, it] { LOCK(context.wallets_mutex); context.wallet_load_fns.erase(it); });
# # ]
184 : 0 : }
185 : :
186 : 0 : void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
187 : : {
188 : 0 : LOCK(context.wallets_mutex);
189 [ # # ]: 0 : for (auto& load_wallet : context.wallet_load_fns) {
190 [ # # # # ]: 0 : load_wallet(interfaces::MakeWallet(context, wallet));
191 : : }
192 : 0 : }
193 : :
194 : : static GlobalMutex g_loading_wallet_mutex;
195 : : static GlobalMutex g_wallet_release_mutex;
196 : : static std::condition_variable g_wallet_release_cv;
197 : : static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
198 : : static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
199 : :
200 : : // Custom deleter for shared_ptr<CWallet>.
201 : 0 : static void FlushAndDeleteWallet(CWallet* wallet)
202 : : {
203 [ # # ]: 0 : const std::string name = wallet->GetName();
204 [ # # ]: 0 : wallet->WalletLogPrintf("Releasing wallet %s..", name);
205 : 0 : delete wallet;
206 : : // Wallet is now released, notify WaitForDeleteWallet, if any.
207 : 0 : {
208 [ # # ]: 0 : LOCK(g_wallet_release_mutex);
209 [ # # ]: 0 : if (g_unloading_wallet_set.erase(name) == 0) {
210 : : // WaitForDeleteWallet was not called for this wallet, all done.
211 [ # # ]: 0 : return;
212 : : }
213 : 0 : }
214 : 0 : g_wallet_release_cv.notify_all();
215 : 0 : }
216 : :
217 : 0 : void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet)
218 : : {
219 : : // Mark wallet for unloading.
220 [ # # ]: 0 : const std::string name = wallet->GetName();
221 : 0 : {
222 [ # # ]: 0 : LOCK(g_wallet_release_mutex);
223 [ # # ]: 0 : g_unloading_wallet_set.insert(name);
224 : : // Do not expect to be the only one removing this wallet.
225 : : // Multiple threads could simultaneously be waiting for deletion.
226 : 0 : }
227 : :
228 : : // Time to ditch our shared_ptr and wait for FlushAndDeleteWallet call.
229 : 0 : wallet.reset();
230 : 0 : {
231 [ # # ]: 0 : WAIT_LOCK(g_wallet_release_mutex, lock);
232 [ # # ]: 0 : while (g_unloading_wallet_set.contains(name)) {
233 [ # # ]: 0 : g_wallet_release_cv.wait(lock);
234 : : }
235 : 0 : }
236 : 0 : }
237 : :
238 : : namespace {
239 : 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)
240 : : {
241 : 0 : try {
242 [ # # ]: 0 : std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
243 [ # # ]: 0 : if (!database) {
244 [ # # # # : 0 : error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
# # # # #
# ]
245 : 0 : return nullptr;
246 : : }
247 : :
248 [ # # # # ]: 0 : context.chain->initMessage(_("Loading wallet…"));
249 [ # # ]: 0 : std::shared_ptr<CWallet> wallet = CWallet::LoadExisting(context, name, std::move(database), error, warnings);
250 [ # # ]: 0 : if (!wallet) {
251 [ # # # # : 0 : error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
# # # # #
# ]
252 : 0 : status = DatabaseStatus::FAILED_LOAD;
253 : 0 : return nullptr;
254 : : }
255 : :
256 [ # # ]: 0 : NotifyWalletLoaded(context, wallet);
257 [ # # ]: 0 : AddWallet(context, wallet);
258 [ # # ]: 0 : wallet->postInitProcess();
259 : :
260 : : // Write the wallet setting
261 [ # # ]: 0 : UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
262 : :
263 : 0 : return wallet;
264 [ # # ]: 0 : } catch (const std::runtime_error& e) {
265 [ - - - - ]: 0 : error = Untranslated(e.what());
266 : 0 : status = DatabaseStatus::FAILED_LOAD;
267 : 0 : return nullptr;
268 : 0 : }
269 : : }
270 : : } // namespace
271 : :
272 : 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)
273 : : {
274 [ # # ]: 0 : auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
275 [ # # ]: 0 : if (!result.second) {
276 [ # # ]: 0 : error = Untranslated("Wallet already loading.");
277 : 0 : status = DatabaseStatus::FAILED_LOAD;
278 : 0 : return nullptr;
279 : : }
280 : 0 : auto wallet = LoadWalletInternal(context, name, load_on_start, options, status, error, warnings);
281 [ # # # # ]: 0 : WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
282 [ # # ]: 0 : return wallet;
283 : 0 : }
284 : :
285 : 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)
286 : : {
287 : : // Wallet must have a non-empty name
288 [ # # ]: 0 : if (name.empty()) {
289 [ # # ]: 0 : error = Untranslated("Wallet name cannot be empty");
290 : 0 : status = DatabaseStatus::FAILED_NEW_UNNAMED;
291 : 0 : return nullptr;
292 : : }
293 : :
294 : 0 : uint64_t wallet_creation_flags = options.create_flags;
295 : 0 : const SecureString& passphrase = options.create_passphrase;
296 : 0 : bool born_encrypted = !passphrase.empty();
297 : :
298 : : // Only descriptor wallets can be created
299 : 0 : Assert(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS);
300 : 0 : options.require_format = DatabaseFormat::SQLITE;
301 : :
302 : :
303 : : // Private keys must be disabled for an external signer wallet
304 [ # # # # ]: 0 : if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
305 [ # # ]: 0 : error = Untranslated("Private keys must be disabled when using an external signer");
306 : 0 : status = DatabaseStatus::FAILED_CREATE;
307 : 0 : return nullptr;
308 : : }
309 : :
310 : : // Do not allow a passphrase when private keys are disabled
311 [ # # # # ]: 0 : if (born_encrypted && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
312 [ # # ]: 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.");
313 : 0 : status = DatabaseStatus::FAILED_CREATE;
314 : 0 : return nullptr;
315 : : }
316 : :
317 : : // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
318 : 0 : std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
319 [ # # ]: 0 : if (!database) {
320 [ # # # # : 0 : error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
# # # # #
# ]
321 : 0 : status = DatabaseStatus::FAILED_VERIFY;
322 : 0 : return nullptr;
323 : : }
324 : :
325 : : // Make the wallet
326 [ # # # # ]: 0 : context.chain->initMessage(_("Creating wallet…"));
327 [ # # ]: 0 : std::shared_ptr<CWallet> wallet = CWallet::CreateNew(context, name, std::move(database), wallet_creation_flags, born_encrypted, error, warnings);
328 [ # # ]: 0 : if (!wallet) {
329 [ # # # # : 0 : error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
# # # # #
# ]
330 : 0 : status = DatabaseStatus::FAILED_CREATE;
331 : 0 : return nullptr;
332 : : }
333 : :
334 : : // Encrypt the wallet
335 [ # # ]: 0 : if (born_encrypted) {
336 [ # # # # ]: 0 : if (!wallet->EncryptWallet(passphrase)) {
337 [ # # # # ]: 0 : error = Untranslated("Error: Wallet created but failed to encrypt.");
338 : 0 : status = DatabaseStatus::FAILED_ENCRYPT;
339 : 0 : return nullptr;
340 : : }
341 : : }
342 : :
343 [ # # # # ]: 0 : WITH_LOCK(wallet->cs_wallet, wallet->LogStats());
344 [ # # ]: 0 : NotifyWalletLoaded(context, wallet);
345 [ # # ]: 0 : AddWallet(context, wallet);
346 [ # # ]: 0 : wallet->postInitProcess();
347 : :
348 : : // Write the wallet settings
349 [ # # ]: 0 : UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
350 : :
351 : 0 : status = DatabaseStatus::SUCCESS;
352 : 0 : return wallet;
353 : 0 : }
354 : :
355 : : // Re-creates wallet from the backup file by renaming and moving it into the wallet's directory.
356 : : // If 'load_after_restore=true', the wallet object will be fully initialized and appended to the context.
357 : 0 : std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& backup_file, const std::string& wallet_name, std::optional<bool> load_on_start, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings, bool load_after_restore, bool allow_unnamed)
358 : : {
359 : : // Error if the wallet name is empty and allow_unnamed == false
360 : : // allow_unnamed == true is only used by migration to migrate an unnamed wallet
361 [ # # # # ]: 0 : if (!allow_unnamed && wallet_name.empty()) {
362 [ # # ]: 0 : error = Untranslated("Wallet name cannot be empty");
363 : 0 : status = DatabaseStatus::FAILED_NEW_UNNAMED;
364 : 0 : return nullptr;
365 : : }
366 : :
367 [ # # ]: 0 : DatabaseOptions options;
368 [ # # ]: 0 : ReadDatabaseArgs(*context.args, options);
369 : 0 : options.require_existing = true;
370 : :
371 [ # # # # : 0 : const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::u8path(wallet_name));
# # # # ]
372 [ # # # # ]: 0 : auto wallet_file = wallet_path / "wallet.dat";
373 : 0 : std::shared_ptr<CWallet> wallet;
374 : 0 : bool wallet_file_copied = false;
375 : 0 : bool created_parent_dir = false;
376 : :
377 : 0 : try {
378 [ # # # # ]: 0 : if (!fs::exists(backup_file)) {
379 [ # # # # ]: 0 : error = Untranslated("Backup file does not exist");
380 : 0 : status = DatabaseStatus::FAILED_INVALID_BACKUP_FILE;
381 : 0 : return nullptr;
382 : : }
383 : :
384 : : // Wallet directories are allowed to exist, but must not contain a .dat file.
385 : : // Any existing wallet database is treated as a hard failure to prevent overwriting.
386 [ # # # # ]: 0 : if (fs::exists(wallet_path)) {
387 : : // If this is a file, it is the db and we don't want to overwrite it.
388 [ # # # # ]: 0 : if (!fs::is_directory(wallet_path)) {
389 [ # # # # : 0 : error = Untranslated(strprintf("Failed to restore wallet. Database file exists '%s'.", fs::PathToString(wallet_path)));
# # ]
390 : 0 : status = DatabaseStatus::FAILED_ALREADY_EXISTS;
391 : 0 : return nullptr;
392 : : }
393 : :
394 : : // Check we are not going to overwrite an existing db file
395 [ # # # # ]: 0 : if (fs::exists(wallet_file)) {
396 [ # # # # : 0 : error = Untranslated(strprintf("Failed to restore wallet. Database file exists in '%s'.", fs::PathToString(wallet_file)));
# # ]
397 : 0 : status = DatabaseStatus::FAILED_ALREADY_EXISTS;
398 : 0 : return nullptr;
399 : : }
400 : : } else {
401 : : // The directory doesn't exist, create it
402 [ # # # # ]: 0 : if (!TryCreateDirectories(wallet_path)) {
403 [ # # # # : 0 : error = Untranslated(strprintf("Failed to restore database path '%s'.", fs::PathToString(wallet_path)));
# # ]
404 : 0 : status = DatabaseStatus::FAILED_ALREADY_EXISTS;
405 : 0 : return nullptr;
406 : : }
407 : : created_parent_dir = true;
408 : : }
409 : :
410 [ # # ]: 0 : fs::copy_file(backup_file, wallet_file, fs::copy_options::none);
411 : 0 : wallet_file_copied = true;
412 : :
413 [ # # ]: 0 : if (load_after_restore) {
414 [ # # # # ]: 0 : wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
415 : : }
416 [ - - ]: 0 : } catch (const std::exception& e) {
417 [ - - ]: 0 : assert(!wallet);
418 [ - - - - : 0 : if (!error.empty()) error += Untranslated("\n");
- - - - ]
419 [ - - - - : 0 : error += Untranslated(strprintf("Unexpected exception: %s", e.what()));
- - ]
420 : 0 : }
421 : :
422 : : // Remove created wallet path only when loading fails
423 [ # # # # ]: 0 : if (load_after_restore && !wallet) {
424 [ # # # # ]: 0 : if (wallet_file_copied) fs::remove(wallet_file);
425 : : // Clean up the parent directory if we created it during restoration.
426 : : // As we have created it, it must be empty after deleting the wallet file.
427 [ # # ]: 0 : if (created_parent_dir) {
428 [ # # # # ]: 0 : Assume(fs::is_empty(wallet_path));
429 [ # # ]: 0 : fs::remove(wallet_path);
430 : : }
431 : : }
432 : :
433 : 0 : return wallet;
434 : 0 : }
435 : :
436 : 11691 : CWallet::CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
437 : 11691 : : m_chain(chain),
438 : 23382 : m_name(name),
439 [ + - ]: 11691 : m_database(std::move(database)),
440 : 23382 : m_scanner(std::make_unique<ChainScanner>(*this))
[ + - + -
- + + - +
- + - +
- ]
441 : : {
442 : 11691 : }
443 : :
444 : 23380 : CWallet::~CWallet()
445 : : {
446 : : // Should not have slots connected at this point.
447 [ - + ]: 11691 : assert(NotifyUnload.empty());
448 : 23380 : }
449 : :
450 : 0 : ChainScanner& CWallet::Scanner() { return *m_scanner; }
451 : 0 : const ChainScanner& CWallet::Scanner() const { return *m_scanner; }
452 : :
453 : : /** @defgroup mapWallet
454 : : *
455 : : * @{
456 : : */
457 : :
458 : 0 : const CWalletTx* CWallet::GetWalletTx(const Txid& hash) const
459 : : {
460 : 0 : AssertLockHeld(cs_wallet);
461 : 0 : const auto it = mapWallet.find(hash);
462 [ # # ]: 0 : if (it == mapWallet.end())
463 : : return nullptr;
464 : 0 : return &(it->second);
465 : : }
466 : :
467 : 0 : void CWallet::UpgradeDescriptorCache()
468 : : {
469 [ # # # # : 0 : if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) || IsLocked() || IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
# # ]
470 : 0 : return;
471 : : }
472 : :
473 [ # # ]: 0 : for (ScriptPubKeyMan* spkm : GetAllScriptPubKeyMans()) {
474 [ # # ]: 0 : DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
475 [ # # ]: 0 : desc_spkm->UpgradeDescriptorCache();
476 : : }
477 : 0 : SetWalletFlag(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
478 : : }
479 : :
480 : : /* Given a wallet passphrase string and an unencrypted master key, determine the proper key
481 : : * derivation parameters (should take at least 100ms) and encrypt the master key. */
482 : 0 : static bool EncryptMasterKey(const SecureString& wallet_passphrase, const CKeyingMaterial& plain_master_key, CMasterKey& master_key)
483 : : {
484 : 0 : constexpr MillisecondsDouble target_time{100};
485 : 0 : CCrypter crypter;
486 [ # # ]: 0 : CMasterKey updated_master_key{master_key};
487 : :
488 : : // Get the weighted average of iterations we can do in 100ms over 2 runs.
489 [ # # ]: 0 : for (int i = 0; i < 2; i++){
490 : 0 : auto start_time{NodeClock::now()};
491 [ # # # # ]: 0 : const bool key_set{crypter.SetKeyFromPassphrase(wallet_passphrase, updated_master_key.vchSalt, updated_master_key.nDeriveIterations, updated_master_key.nDerivationMethod)};
492 : 0 : auto elapsed_time{NodeClock::now() - start_time};
493 [ # # ]: 0 : if (!key_set) {
494 : : return false;
495 : : }
496 : :
497 [ # # ]: 0 : if (elapsed_time <= 0s) {
498 : : // We are probably in a test with a mocked clock.
499 : 0 : updated_master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
500 : 0 : break;
501 : : }
502 : :
503 : : // target_iterations : elapsed_iterations :: target_time : elapsed_time
504 : 0 : const double target_iterations{updated_master_key.nDeriveIterations * target_time / elapsed_time};
505 [ # # # # ]: 0 : if (target_iterations < 1 || target_iterations > std::numeric_limits<unsigned int>::max()) {
506 : : return false;
507 : : }
508 : : // Get the weighted average with previous runs. Use 64-bit math so the
509 : : // sum cannot wrap; the average of two unsigned int values fits in one.
510 : 0 : updated_master_key.nDeriveIterations = (uint64_t{updated_master_key.nDeriveIterations} * i + static_cast<unsigned int>(target_iterations)) / (i + 1);
511 : : }
512 : :
513 [ # # ]: 0 : if (updated_master_key.nDeriveIterations < CMasterKey::DEFAULT_DERIVE_ITERATIONS) {
514 : 0 : updated_master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
515 : : }
516 : :
517 [ # # # # : 0 : if (!crypter.SetKeyFromPassphrase(wallet_passphrase, updated_master_key.vchSalt, updated_master_key.nDeriveIterations, updated_master_key.nDerivationMethod)) {
# # ]
518 : : return false;
519 : : }
520 [ # # # # ]: 0 : if (!crypter.Encrypt(plain_master_key, updated_master_key.vchCryptedKey)) {
521 : : return false;
522 : : }
523 : :
524 : 0 : master_key = std::move(updated_master_key);
525 : 0 : return true;
526 : 0 : }
527 : :
528 : 0 : static bool DecryptMasterKey(const SecureString& wallet_passphrase, const CMasterKey& master_key, CKeyingMaterial& plain_master_key)
529 : : {
530 : 0 : CCrypter crypter;
531 [ # # # # : 0 : if (!crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod)) {
# # ]
532 : : return false;
533 : : }
534 [ # # # # : 0 : if (!crypter.Decrypt(master_key.vchCryptedKey, plain_master_key)) {
# # ]
535 : 0 : return false;
536 : : }
537 : :
538 : : return true;
539 : 0 : }
540 : :
541 : 0 : static util::Unexpected<WalletError> UnlockPassphraseError(const SecureString& passphrase)
542 : : {
543 [ # # ]: 0 : bilingual_str message;
544 [ # # ]: 0 : if (passphrase.find('\0') != std::string::npos) {
545 : : // The passphrase has a null character (see #27067 for details)
546 [ # # ]: 0 : message = _("Error: The wallet passphrase entered is incorrect. "
547 : : "It contains a null character (ie - a zero byte). "
548 : : "If the passphrase was set with a version of this software prior to 25.0, "
549 : : "please try again with only the characters up to — but not including — "
550 : : "the first null character. If this is successful, please set a new "
551 : 0 : "passphrase to avoid this issue in the future.");
552 [ # # ]: 0 : } else if (passphrase.empty()) {
553 [ # # ]: 0 : message = _("Error: The wallet passphrase was not provided");
554 : : } else {
555 [ # # ]: 0 : message = _("Error: The wallet passphrase entered was incorrect.");
556 : : }
557 : 0 : return util::Unexpected{WalletError{WalletErrorCode::PassphraseIncorrect, std::move(message)}};
558 : 0 : }
559 : :
560 : 0 : util::Expected<void, WalletError> CWallet::Unlock(const SecureString& strWalletPassphrase)
561 : : {
562 : 0 : CKeyingMaterial plain_master_key;
563 : :
564 : 0 : {
565 [ # # ]: 0 : LOCK(cs_wallet);
566 [ # # # # ]: 0 : for (const auto& [_, master_key] : mapMasterKeys)
567 : : {
568 [ # # # # ]: 0 : if (!DecryptMasterKey(strWalletPassphrase, master_key, plain_master_key)) {
569 : 0 : continue; // try another master key
570 : : }
571 [ # # # # ]: 0 : if (Unlock(plain_master_key)) {
572 : : // Now that we've unlocked, upgrade the descriptor cache
573 [ # # ]: 0 : UpgradeDescriptorCache();
574 : :
575 [ # # # # ]: 0 : if (!m_last_decrypted_features || *m_last_decrypted_features != WALLET_CLIENT_FEATURES) {
576 : : // Write the current wallet client features to LAST_DECRYPTED_FEATURES.
577 : : // This must be done after all automatic upgrades so that those upgrades can be
578 : : // performed in an upgrade-downgrade-upgrade scenario.
579 [ # # ]: 0 : WalletBatch batch(GetDatabase());
580 [ # # # # ]: 0 : if (batch.WriteLastDecryptedFeatures()) {
581 [ # # ]: 0 : SetLastDecryptedFeatures(WALLET_CLIENT_FEATURES);
582 : : }
583 : 0 : }
584 : :
585 [ # # ]: 0 : return {};
586 : : }
587 : : }
588 : 0 : }
589 [ # # ]: 0 : return UnlockPassphraseError(strWalletPassphrase);
590 : 0 : }
591 : :
592 : 0 : util::Expected<void, WalletError> CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
593 : : {
594 : 0 : bool fWasLocked = IsLocked();
595 : :
596 : 0 : {
597 [ # # ]: 0 : LOCK2(m_relock_mutex, cs_wallet);
598 [ # # ]: 0 : Lock();
599 : :
600 : 0 : CKeyingMaterial plain_master_key;
601 [ # # # # ]: 0 : for (auto& [master_key_id, master_key] : mapMasterKeys)
602 : : {
603 [ # # # # ]: 0 : if (!DecryptMasterKey(strOldWalletPassphrase, master_key, plain_master_key)) {
604 [ # # ]: 0 : return UnlockPassphraseError(strOldWalletPassphrase);
605 : : }
606 [ # # # # ]: 0 : if (Unlock(plain_master_key))
607 : : {
608 [ # # # # ]: 0 : if (fWasLocked) Lock();
609 [ # # ]: 0 : CMasterKey new_master_key{master_key};
610 [ # # # # ]: 0 : if (!EncryptMasterKey(strNewWalletPassphrase, plain_master_key, new_master_key)) {
611 [ # # ]: 0 : return util::Unexpected{WalletError{WalletErrorCode::GenericError, _("Error: Unable to encrypt encryption key with new passphrase")}};
612 : : }
613 [ # # # # : 0 : if (!WalletBatch(GetDatabase()).WriteMasterKey(master_key_id, new_master_key)) {
# # ]
614 [ # # ]: 0 : return util::Unexpected{WalletError{WalletErrorCode::GenericError, _("Error: Writing the new encryption key to the wallet database failed")}};
615 : : }
616 [ # # ]: 0 : WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i", new_master_key.nDeriveIterations);
617 : 0 : master_key = std::move(new_master_key);
618 : 0 : return {};
619 : 0 : }
620 : : }
621 [ # # # # : 0 : }
# # # # ]
622 : :
623 : 0 : return UnlockPassphraseError(strOldWalletPassphrase);
624 : : }
625 : :
626 : 11691 : void CWallet::SetLastBlockProcessedInMem(int block_height, uint256 block_hash)
627 : : {
628 : 11691 : AssertLockHeld(cs_wallet);
629 : :
630 : 11691 : m_last_block_processed = block_hash;
631 : 11691 : m_last_block_processed_height = block_height;
632 : 11691 : }
633 : :
634 : 11691 : void CWallet::SetLastBlockProcessed(int block_height, uint256 block_hash)
635 : : {
636 : 11691 : AssertLockHeld(cs_wallet);
637 : :
638 : 11691 : SetLastBlockProcessedInMem(block_height, block_hash);
639 : 11691 : WriteBestBlock();
640 : 11691 : }
641 : :
642 : 0 : std::set<Txid> CWallet::GetConflicts(const Txid& txid) const
643 : : {
644 : 0 : std::set<Txid> result;
645 : 0 : AssertLockHeld(cs_wallet);
646 : :
647 : 0 : const auto it = mapWallet.find(txid);
648 [ # # ]: 0 : if (it == mapWallet.end())
649 : : return result;
650 [ # # ]: 0 : const CWalletTx& wtx = it->second;
651 : :
652 [ # # ]: 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
653 : :
654 [ # # # # : 0 : for (const CTxIn& txin : wtx.GetTx()->vin)
# # ]
655 : : {
656 [ # # ]: 0 : if (mapTxSpends.count(txin.prevout) <= 1)
657 : 0 : continue; // No conflict if zero or one spends
658 : 0 : range = mapTxSpends.equal_range(txin.prevout);
659 [ # # ]: 0 : for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
660 [ # # ]: 0 : result.insert(_it->second);
661 : : }
662 : : return result;
663 : 0 : }
664 : :
665 : 0 : bool CWallet::HasWalletSpend(const CTransactionRef& tx) const
666 : : {
667 : 0 : AssertLockHeld(cs_wallet);
668 : 0 : const Txid& txid = tx->GetHash();
669 [ # # # # ]: 0 : for (unsigned int i = 0; i < tx->vout.size(); ++i) {
670 [ # # ]: 0 : if (IsSpent(COutPoint(txid, i))) {
671 : : return true;
672 : : }
673 : : }
674 : : return false;
675 : : }
676 : :
677 : 0 : void CWallet::Close()
678 : : {
679 : 0 : GetDatabase().Close();
680 : 0 : }
681 : :
682 : 0 : std::set<CWalletTx*, WalletTxOrderComparator> CWallet::GetMalleatedVariants(const CWalletTx& wtx)
683 : : {
684 : 0 : AssertLockHeld(cs_wallet);
685 [ # # ]: 0 : std::set<CWalletTx*, WalletTxOrderComparator> txs;
686 : :
687 : : // Coinbases cannot be malleated
688 [ # # # # ]: 0 : if (wtx.IsCoinBase()) return txs;
689 : :
690 : : // Only transactions that have non-witness inputs can be malleated
691 [ # # # # : 0 : if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.IsNull(); })) {
# # # # ]
692 : : return txs;
693 : : }
694 : :
695 : : // All variants spend wtx's first input, so a single lookup finds every candidate
696 : 0 : bool found_self = false;
697 [ # # # # ]: 0 : const auto [begin, end] = mapTxSpends.equal_range(wtx.GetTx()->vin.front().prevout);
698 [ # # ]: 0 : for (auto it = begin; it != end; ++it) {
699 : 0 : auto entry = mapWallet.find(it->second);
700 [ # # # # : 0 : if (!Assume(entry != mapWallet.end())) continue; // sanity-check: mapTxSpends has txs that are in mapWallet
# # ]
701 [ # # ]: 0 : const bool is_self = &entry->second == &wtx;
702 : 0 : found_self |= is_self;
703 [ # # # # : 0 : if (is_self || wtx.IsMalleation(entry->second)) {
# # ]
704 [ # # # # ]: 0 : Assume(txs.insert(&entry->second).second);
705 : : }
706 : : }
707 : : // wtx should always be found as this function is always called after AddToSpends
708 [ # # ]: 0 : Assert(found_self);
709 : : return txs;
710 : 0 : }
711 : :
712 : 0 : void CWallet::SyncMalleatedTxMetadata(WalletBatch& batch, const CWalletTx& wtx)
713 : : {
714 : 0 : const auto txs = GetMalleatedVariants(wtx);
715 [ # # ]: 0 : if (txs.size() <= 1) return; // no variants, nothing to do
716 : :
717 : : // First tx is the oldest one (smallest nOrderPos)
718 : 0 : const CWalletTx* copyFrom = *txs.begin();
719 : :
720 : : // The metadata that is kept in sync between malleated variants.
721 : : // nTimeReceived, nOrderPos and cached members are not copied on purpose.
722 : 0 : const auto metadata = [](auto& tx) {
723 : 0 : return std::tie(tx.m_from, tx.m_message, tx.m_comment, tx.m_comment_to,
724 : 0 : tx.m_replaces_txid, tx.m_replaced_by_txid,
725 : 0 : tx.m_messages, tx.m_payment_requests, tx.nTimeSmart);
726 : : };
727 : :
728 : : // Now copy data from copyFrom to rest:
729 [ # # ]: 0 : for (CWalletTx* copyTo : txs) {
730 [ # # ]: 0 : if (copyTo == copyFrom) continue;
731 [ # # ]: 0 : metadata(*copyTo) = metadata(*copyFrom);
732 [ # # ]: 0 : (void)batch.WriteTxMetadata(*copyTo);
733 : : }
734 : 0 : }
735 : :
736 : : /**
737 : : * Outpoint is spent if any non-conflicted transaction
738 : : * spends it:
739 : : */
740 : 284055 : bool CWallet::IsSpent(const COutPoint& outpoint) const
741 : : {
742 : 284055 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
743 : 284055 : range = mapTxSpends.equal_range(outpoint);
744 : :
745 [ - + ]: 284055 : for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
746 : 0 : const Txid& txid = it->second;
747 : 0 : const auto mit = mapWallet.find(txid);
748 [ # # ]: 0 : if (mit != mapWallet.end()) {
749 [ # # ]: 0 : const auto& wtx = mit->second;
750 [ # # # # : 0 : if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted())
# # ]
751 : : return true; // Spent
752 : : }
753 : : }
754 : : return false;
755 : : }
756 : :
757 : 0 : CWallet::SpendType CWallet::HowSpent(const COutPoint& outpoint) const
758 : : {
759 : 0 : SpendType st{SpendType::UNSPENT};
760 : :
761 : 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
762 : 0 : range = mapTxSpends.equal_range(outpoint);
763 : :
764 [ # # ]: 0 : for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
765 : 0 : const Txid& txid = it->second;
766 : 0 : const auto mit = mapWallet.find(txid);
767 [ # # ]: 0 : if (mit != mapWallet.end()) {
768 [ # # ]: 0 : const auto& wtx = mit->second;
769 [ # # ]: 0 : if (wtx.isConfirmed()) return SpendType::CONFIRMED;
770 [ # # ]: 0 : if (wtx.InMempool()) {
771 : : st = SpendType::MEMPOOL;
772 [ # # # # : 0 : } else if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted()) {
# # ]
773 [ # # ]: 0 : if (st == SpendType::UNSPENT) st = SpendType::NONMEMPOOL;
774 : : }
775 : : }
776 : : }
777 : : return st;
778 : : }
779 : :
780 : 0 : void CWallet::AddToSpends(const COutPoint& outpoint, const Txid& txid)
781 : : {
782 : 0 : mapTxSpends.insert(std::make_pair(outpoint, txid));
783 : :
784 : 0 : UnlockCoin(outpoint);
785 : 0 : }
786 : :
787 : :
788 : 0 : void CWallet::AddToSpends(const CWalletTx& wtx)
789 : : {
790 [ # # ]: 0 : if (wtx.IsCoinBase()) // Coinbases don't spend anything!
791 : : return;
792 : :
793 [ # # # # ]: 0 : for (const CTxIn& txin : wtx.GetTx()->vin)
794 : 0 : AddToSpends(txin.prevout, wtx.GetHash());
795 : : }
796 : :
797 : 0 : bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
798 : : {
799 : : // Only descriptor wallets can be encrypted
800 : 0 : Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
801 : :
802 [ # # ]: 0 : if (HasEncryptionKeys())
803 : : return false;
804 : :
805 : 0 : CKeyingMaterial plain_master_key;
806 : :
807 [ # # ]: 0 : plain_master_key.resize(WALLET_CRYPTO_KEY_SIZE);
808 [ # # ]: 0 : GetStrongRandBytes(plain_master_key);
809 : :
810 [ # # ]: 0 : CMasterKey master_key;
811 : :
812 [ # # ]: 0 : master_key.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
813 [ # # ]: 0 : GetStrongRandBytes(master_key.vchSalt);
814 : :
815 [ # # # # ]: 0 : if (!EncryptMasterKey(strWalletPassphrase, plain_master_key, master_key)) {
816 : : return false;
817 : : }
818 [ # # ]: 0 : WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i", master_key.nDeriveIterations);
819 : :
820 : 0 : {
821 [ # # # # ]: 0 : LOCK2(m_relock_mutex, cs_wallet);
822 : 0 : const unsigned int new_master_key_id{nMasterKeyMaxID + 1};
823 [ # # # # : 0 : if (!RunWithinTxn(GetDatabase(), /*process_desc=*/"wallet encryption", [&](WalletBatch& batch) {
# # ]
824 [ # # ]: 0 : if (!batch.WriteMasterKey(new_master_key_id, master_key)) {
825 : : return false;
826 : : }
827 [ # # ]: 0 : for (const auto& spk_man_pair : m_spk_managers) {
828 [ # # ]: 0 : if (!spk_man_pair.second->Encrypt(plain_master_key, &batch)) {
829 : : return false;
830 : : }
831 : : }
832 : : return true;
833 : : })) {
834 : : return false;
835 : : }
836 : :
837 : 0 : nMasterKeyMaxID = new_master_key_id;
838 [ # # ]: 0 : mapMasterKeys[new_master_key_id] = std::move(master_key);
839 : :
840 [ # # ]: 0 : Lock();
841 [ # # # # ]: 0 : if (!Unlock(strWalletPassphrase)) {
842 : : return false;
843 : : }
844 : :
845 [ # # ]: 0 : SetupWalletGeneration();
846 : :
847 [ # # ]: 0 : Lock();
848 : :
849 : : // Need to completely rewrite the wallet file; if we don't, the database might keep
850 : : // bits of the unencrypted private key in slack space in the database file.
851 [ # # ]: 0 : GetDatabase().Rewrite();
852 [ # # # # ]: 0 : }
853 [ # # ]: 0 : NotifyStatusChanged(this);
854 : :
855 : : return true;
856 : 0 : }
857 : :
858 : 0 : DBErrors CWallet::ReorderTransactions()
859 : : {
860 : 0 : LOCK(cs_wallet);
861 [ # # ]: 0 : WalletBatch batch(GetDatabase());
862 : :
863 : : // Old wallets didn't have any defined order for transactions
864 : : // Probably a bad idea to change the output of this
865 : :
866 : : // First: get all CWalletTx into a sorted-by-time multimap.
867 : 0 : typedef std::multimap<int64_t, CWalletTx*> TxItems;
868 : 0 : TxItems txByTime;
869 : :
870 [ # # # # ]: 0 : for (auto& entry : mapWallet)
871 : : {
872 : 0 : CWalletTx* wtx = &entry.second;
873 [ # # ]: 0 : txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
874 : : }
875 : :
876 : 0 : nOrderPosNext = 0;
877 : 0 : std::vector<int64_t> nOrderPosOffsets;
878 [ # # ]: 0 : for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
879 : : {
880 [ # # ]: 0 : CWalletTx *const pwtx = (*it).second;
881 : 0 : int64_t& nOrderPos = pwtx->nOrderPos;
882 : :
883 [ # # ]: 0 : if (nOrderPos == -1)
884 : : {
885 : 0 : nOrderPos = nOrderPosNext++;
886 [ # # ]: 0 : nOrderPosOffsets.push_back(nOrderPos);
887 : :
888 [ # # # # ]: 0 : if (!batch.WriteTxMetadata(*pwtx))
889 : : return DBErrors::LOAD_FAIL;
890 : : }
891 : : else
892 : : {
893 : 0 : int64_t nOrderPosOff = 0;
894 [ # # ]: 0 : for (const int64_t& nOffsetStart : nOrderPosOffsets)
895 : : {
896 [ # # ]: 0 : if (nOrderPos >= nOffsetStart)
897 : 0 : ++nOrderPosOff;
898 : : }
899 : 0 : nOrderPos += nOrderPosOff;
900 [ # # ]: 0 : nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
901 : :
902 [ # # ]: 0 : if (!nOrderPosOff)
903 : 0 : continue;
904 : :
905 : : // Since we're changing the order, write it back
906 [ # # # # ]: 0 : if (!batch.WriteTxMetadata(*pwtx))
907 : : return DBErrors::LOAD_FAIL;
908 : : }
909 : : }
910 [ # # ]: 0 : batch.WriteOrderPosNext(nOrderPosNext);
911 : :
912 : : return DBErrors::LOAD_OK;
913 [ # # ]: 0 : }
914 : :
915 : 0 : int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
916 : : {
917 : 0 : AssertLockHeld(cs_wallet);
918 : 0 : int64_t nRet = nOrderPosNext++;
919 [ # # ]: 0 : if (batch) {
920 : 0 : batch->WriteOrderPosNext(nOrderPosNext);
921 : : } else {
922 [ # # ]: 0 : WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
923 : : }
924 : 0 : return nRet;
925 : : }
926 : :
927 : 8180 : void CWallet::MarkDirty()
928 : : {
929 : 8180 : {
930 : 8180 : LOCK(cs_wallet);
931 [ + - + - ]: 8180 : for (auto& [_, wtx] : mapWallet)
932 : 0 : wtx.MarkDirty();
933 : 8180 : }
934 : 8180 : }
935 : :
936 : 0 : bool CWallet::MarkReplaced(const Txid& originalHash, const Txid& newHash)
937 : : {
938 : 0 : LOCK(cs_wallet);
939 : :
940 : 0 : auto mi = mapWallet.find(originalHash);
941 : :
942 : : // There is a bug if MarkReplaced is not called on an existing wallet transaction.
943 [ # # ]: 0 : assert(mi != mapWallet.end());
944 : :
945 [ # # ]: 0 : CWalletTx& wtx = (*mi).second;
946 : :
947 : : // Ensure for now that we're not overwriting data
948 [ # # ]: 0 : Assert(!wtx.m_replaced_by_txid);
949 : :
950 [ # # ]: 0 : wtx.m_replaced_by_txid = newHash;
951 : :
952 : : // Refresh mempool status without waiting for transactionRemovedFromMempool or transactionAddedToMempool
953 [ # # ]: 0 : RefreshMempoolStatus(wtx, chain());
954 : :
955 [ # # ]: 0 : WalletBatch batch(GetDatabase());
956 : :
957 : 0 : bool success = true;
958 [ # # # # ]: 0 : if (!batch.WriteTxMetadata(wtx)) {
959 [ # # # # : 0 : WalletLogPrintf("%s: Updating batch tx %s failed", __func__, wtx.GetHash().ToString());
# # ]
960 : 0 : success = false;
961 : : }
962 : :
963 : : // The new transaction also replaces any malleated variants of wtx,
964 : : // so bumpfee refuses to bump them afterwards
965 [ # # # # ]: 0 : for (CWalletTx* variant : GetMalleatedVariants(wtx)) {
966 [ # # ]: 0 : if (variant == &wtx) continue;
967 [ # # ]: 0 : variant->m_replaced_by_txid = newHash;
968 [ # # # # ]: 0 : if (!batch.WriteTxMetadata(*variant)) {
969 [ # # # # : 0 : WalletLogPrintf("%s: Updating variant tx %s failed", __func__, variant->GetHash().ToString());
# # ]
970 : 0 : success = false;
971 : : }
972 : : }
973 : :
974 [ # # ]: 0 : NotifyTransactionChanged(originalHash, CT_UPDATED);
975 : :
976 : 0 : return success;
977 [ # # ]: 0 : }
978 : :
979 : 0 : void CWallet::SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
980 : : {
981 : 0 : AssertLockHeld(cs_wallet);
982 : 0 : const CWalletTx* srctx = GetWalletTx(hash);
983 [ # # ]: 0 : if (!srctx) return;
984 : :
985 : 0 : CTxDestination dst;
986 [ # # # # : 0 : if (ExtractDestination(srctx->GetTx()->vout[n].scriptPubKey, dst)) {
# # # # ]
987 [ # # # # ]: 0 : if (IsMine(dst)) {
988 [ # # # # ]: 0 : if (used != IsAddressPreviouslySpent(dst)) {
989 [ # # ]: 0 : if (used) {
990 [ # # ]: 0 : tx_destinations.insert(dst);
991 : : }
992 [ # # ]: 0 : SetAddressPreviouslySpent(batch, dst, used);
993 : : }
994 : : }
995 : : }
996 : 0 : }
997 : :
998 : 0 : bool CWallet::IsSpentKey(const CScript& scriptPubKey) const
999 : : {
1000 : 0 : AssertLockHeld(cs_wallet);
1001 : 0 : CTxDestination dest;
1002 [ # # # # ]: 0 : if (!ExtractDestination(scriptPubKey, dest)) {
1003 : : return false;
1004 : : }
1005 [ # # # # ]: 0 : if (IsAddressPreviouslySpent(dest)) {
1006 : 0 : return true;
1007 : : }
1008 : : return false;
1009 : 0 : }
1010 : :
1011 : 0 : CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx, bool rescanning_old_block)
1012 : : {
1013 : 0 : LOCK(cs_wallet);
1014 : :
1015 [ # # ]: 0 : WalletBatch batch(GetDatabase());
1016 : :
1017 [ # # ]: 0 : Txid hash = tx->GetHash();
1018 : :
1019 [ # # # # ]: 0 : if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
1020 : : // Mark used destinations
1021 : 0 : std::set<CTxDestination> tx_destinations;
1022 : :
1023 [ # # ]: 0 : for (const CTxIn& txin : tx->vin) {
1024 : 0 : const COutPoint& op = txin.prevout;
1025 [ # # ]: 0 : SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
1026 : : }
1027 : :
1028 [ # # ]: 0 : MarkDestinationsDirty(tx_destinations);
1029 : 0 : }
1030 : :
1031 : : // Inserts only if not already there, returns tx inserted or tx found
1032 [ # # ]: 0 : auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(tx, state));
1033 [ # # ]: 0 : CWalletTx& wtx = (*ret.first).second;
1034 : 0 : bool fInsertedNew = ret.second;
1035 [ # # # # : 0 : bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
# # ]
1036 [ # # ]: 0 : if (fInsertedNew) {
1037 [ # # ]: 0 : wtx.nTimeReceived = GetTime();
1038 [ # # ]: 0 : wtx.nOrderPos = IncOrderPosNext(&batch);
1039 [ # # # # ]: 0 : wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1040 [ # # ]: 0 : wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block);
1041 [ # # ]: 0 : AddToSpends(wtx);
1042 [ # # ]: 0 : SyncMalleatedTxMetadata(batch, wtx);
1043 : :
1044 : : // Update birth time when tx time is older than it.
1045 [ # # # # ]: 0 : MaybeUpdateBirthTime(wtx.GetTxTime());
1046 : :
1047 [ # # # # ]: 0 : if (!batch.WriteFullTx(wtx)) {
1048 : : return nullptr;
1049 : : }
1050 : : }
1051 : :
1052 : 0 : if (!fInsertedNew)
1053 : : {
1054 : 0 : try {
1055 [ # # # # : 0 : fUpdated |= wtx.Update(tx, state, batch, fUpdated);
# # ]
1056 [ - - ]: 0 : } catch (const std::ios_base::failure& e) {
1057 [ - - ]: 0 : WalletLogPrintf("Error: Unable to write tx update, %s", e.what());
1058 : 0 : return nullptr;
1059 : 0 : }
1060 : : }
1061 : :
1062 : : // Mark inactive coinbase transactions and their descendants as abandoned
1063 [ # # # # ]: 0 : if (wtx.IsCoinBase() && wtx.isInactive()) {
1064 [ # # ]: 0 : std::vector<CWalletTx*> txs{&wtx};
1065 : :
1066 : 0 : TxStateInactive inactive_state = TxStateInactive{/*abandoned=*/true};
1067 : :
1068 [ # # ]: 0 : while (!txs.empty()) {
1069 : 0 : CWalletTx* desc_tx = txs.back();
1070 [ # # ]: 0 : txs.pop_back();
1071 [ # # ]: 0 : desc_tx->m_state = inactive_state;
1072 : : // Break caches since we have changed the state
1073 : 0 : desc_tx->MarkDirty();
1074 [ # # ]: 0 : batch.WriteTxMetadata(*desc_tx);
1075 [ # # # # ]: 0 : MarkInputsDirty(desc_tx->GetTx());
1076 [ # # # # : 0 : for (unsigned int i = 0; i < desc_tx->GetTx()->vout.size(); ++i) {
# # # # ]
1077 [ # # ]: 0 : COutPoint outpoint(desc_tx->GetHash(), i);
1078 : 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(outpoint);
1079 [ # # ]: 0 : for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
1080 : 0 : const auto wit = mapWallet.find(it->second);
1081 [ # # ]: 0 : if (wit != mapWallet.end()) {
1082 [ # # ]: 0 : txs.push_back(&wit->second);
1083 : : }
1084 : : }
1085 : : }
1086 : : }
1087 : 0 : }
1088 : :
1089 : : //// debug print
1090 [ # # ]: 0 : std::string status{"no-change"};
1091 [ # # ]: 0 : if (fInsertedNew || fUpdated) {
1092 [ # # # # ]: 0 : status = fInsertedNew ? (fUpdated ? "new, update" : "new") : "update";
1093 : : }
1094 [ # # # # ]: 0 : WalletLogPrintf("AddToWallet %s %s %s", hash.ToString(), status, TxStateString(state));
1095 : :
1096 : : // Break debit/credit balance caches:
1097 : 0 : wtx.MarkDirty();
1098 : :
1099 : : // Cache the outputs that belong to the wallet
1100 [ # # ]: 0 : RefreshTXOsFromTx(wtx);
1101 : :
1102 : : // Notify UI of new or updated transaction
1103 [ # # # # ]: 0 : NotifyTransactionChanged(hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1104 : :
1105 : : #if HAVE_SYSTEM
1106 : : // notify an external script when a wallet transaction comes in or is updated
1107 [ # # ]: 0 : std::string strCmd = m_notify_tx_changed_script;
1108 : :
1109 [ # # ]: 0 : if (!strCmd.empty())
1110 : : {
1111 [ # # # # : 0 : ReplaceAll(strCmd, "%s", hash.GetHex());
# # ]
1112 [ # # ]: 0 : if (auto* conf = wtx.state<TxStateConfirmed>())
1113 : : {
1114 [ # # # # ]: 0 : ReplaceAll(strCmd, "%b", conf->confirmed_block_hash.GetHex());
1115 [ # # # # ]: 0 : ReplaceAll(strCmd, "%h", ToString(conf->confirmed_block_height));
1116 : : } else {
1117 [ # # ]: 0 : ReplaceAll(strCmd, "%b", "unconfirmed");
1118 [ # # ]: 0 : ReplaceAll(strCmd, "%h", "-1");
1119 : : }
1120 : : #ifndef WIN32
1121 : : // Substituting the wallet name isn't currently supported on windows
1122 : : // because windows shell escaping has not been implemented yet:
1123 : : // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
1124 : : // A few ways it could be implemented in the future are described in:
1125 : : // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
1126 [ # # # # ]: 0 : ReplaceAll(strCmd, "%w", ShellEscape(GetName()));
1127 : : #endif
1128 [ # # ]: 0 : std::thread t(runCommand, strCmd);
1129 [ # # ]: 0 : t.detach(); // thread runs free
1130 : 0 : }
1131 : : #endif
1132 : :
1133 : 0 : return &wtx;
1134 [ # # ]: 0 : }
1135 : :
1136 : 0 : bool CWallet::LoadToWallet(CWalletTx&& wtx_in)
1137 : : {
1138 : 0 : const auto& ins = mapWallet.emplace(wtx_in.GetHash(), std::move(wtx_in));
1139 [ # # ]: 0 : CWalletTx& wtx = ins.first->second;
1140 [ # # ]: 0 : if (!ins.second) {
1141 : : return false;
1142 : : }
1143 : : // If wallet doesn't have a chain (e.g when using bitcoin-wallet tool),
1144 : : // don't bother to update txn.
1145 [ # # ]: 0 : if (HaveChain()) {
1146 : 0 : wtx.updateState(chain());
1147 : : }
1148 : 0 : wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1149 : 0 : AddToSpends(wtx);
1150 [ # # # # ]: 0 : for (const CTxIn& txin : wtx.GetTx()->vin) {
1151 : 0 : auto it = mapWallet.find(txin.prevout.hash);
1152 [ # # ]: 0 : if (it != mapWallet.end()) {
1153 [ # # ]: 0 : CWalletTx& prevtx = it->second;
1154 [ # # ]: 0 : if (auto* prev = prevtx.state<TxStateBlockConflicted>()) {
1155 : 0 : MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, wtx.GetHash());
1156 : : }
1157 : : }
1158 : : }
1159 : :
1160 : : // Update birth time when tx time is older than it.
1161 : 0 : MaybeUpdateBirthTime(wtx.GetTxTime());
1162 : :
1163 : : // Make sure the tx outputs are known by the wallet
1164 : 0 : RefreshTXOsFromTx(wtx);
1165 : 0 : return true;
1166 : : }
1167 : :
1168 : 0 : bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const SyncTxState& state, bool rescanning_old_block)
1169 : : {
1170 [ # # ]: 0 : const CTransaction& tx = *ptx;
1171 : 0 : {
1172 : 0 : AssertLockHeld(cs_wallet);
1173 : :
1174 [ # # ]: 0 : if (auto* conf = std::get_if<TxStateConfirmed>(&state)) {
1175 [ # # ]: 0 : for (const CTxIn& txin : tx.vin) {
1176 : 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1177 [ # # ]: 0 : while (range.first != range.second) {
1178 [ # # ]: 0 : if (range.first->second != tx.GetHash()) {
1179 [ # # # # : 0 : WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)", tx.GetHash().ToString(), conf->confirmed_block_hash.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
# # # # ]
1180 : 0 : MarkConflicted(conf->confirmed_block_hash, conf->confirmed_block_height, range.first->second);
1181 : : }
1182 : 0 : range.first++;
1183 : : }
1184 : : }
1185 : : }
1186 : :
1187 : 0 : bool fExisted = mapWallet.contains(tx.GetHash());
1188 [ # # # # : 0 : if (fExisted || IsMine(tx) || IsFromMe(tx))
# # ]
1189 : : {
1190 : : /* Check if any keys in the wallet keypool that were supposed to be unused
1191 : : * have appeared in a new transaction. If so, remove those keys from the keypool.
1192 : : * This can happen when restoring an old wallet backup that does not contain
1193 : : * the mostly recently created transactions from newer versions of the wallet.
1194 : : */
1195 : :
1196 : : // loop though all outputs
1197 [ # # ]: 0 : for (const CTxOut& txout: tx.vout) {
1198 [ # # ]: 0 : for (const auto& spk_man : GetScriptPubKeyMans(txout.scriptPubKey)) {
1199 [ # # # # ]: 0 : for (auto &dest : spk_man->MarkUnusedAddresses(txout.scriptPubKey)) {
1200 : : // If internal flag is not defined try to infer it from the ScriptPubKeyMan
1201 [ # # ]: 0 : if (!dest.internal.has_value()) {
1202 [ # # ]: 0 : dest.internal = IsInternalScriptPubKeyMan(spk_man);
1203 : : }
1204 : :
1205 : : // skip if can't determine whether it's a receiving address or not
1206 [ # # ]: 0 : if (!dest.internal.has_value()) continue;
1207 : :
1208 : : // If this is a receiving address and it's not in the address book yet
1209 : : // (e.g. it wasn't generated on this node or we're restoring from backup)
1210 : : // add it to the address book for proper transaction accounting
1211 [ # # # # : 0 : if (!*dest.internal && !FindAddressBookEntry(dest.dest, /* allow_change= */ false)) {
# # ]
1212 [ # # # # ]: 0 : SetAddressBook(dest.dest, "", AddressPurpose::RECEIVE);
1213 : : }
1214 : 0 : }
1215 : 0 : }
1216 : : }
1217 : :
1218 : : // Block disconnection override an abandoned tx as unconfirmed
1219 : : // which means user may have to call abandontransaction again
1220 [ # # ]: 0 : TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
1221 [ # # # # : 0 : CWalletTx* wtx = AddToWallet(MakeTransactionRef(tx), tx_state, /*update_wtx=*/nullptr, rescanning_old_block);
# # ]
1222 [ # # ]: 0 : if (!wtx) {
1223 : : // Can only be nullptr if there was a db write error (missing db, read-only db or a db engine internal writing error).
1224 : : // As we only store arriving transaction in this process, and we don't want an inconsistent state, let's throw an error.
1225 [ # # ]: 0 : throw std::runtime_error("DB error adding transaction to wallet, write failed");
1226 : : }
1227 : : return true;
1228 : : }
1229 : : }
1230 : : return false;
1231 : : }
1232 : :
1233 : 0 : bool CWallet::TransactionCanBeAbandoned(const Txid& hashTx) const
1234 : : {
1235 : 0 : LOCK(cs_wallet);
1236 [ # # ]: 0 : const CWalletTx* wtx = GetWalletTx(hashTx);
1237 : 0 : return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 && !wtx->InMempool();
[ # # # #
# # # # #
# # # ]
1238 : 0 : }
1239 : :
1240 : 0 : void CWallet::UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1241 : : {
1242 : : // Find all other txs in our wallet that spend utxos from this parent
1243 : : // so that we can mark them as mempool-conflicted by this new tx.
1244 [ # # # # : 0 : for (long unsigned int i = 0; i < parent_wtx.GetTx()->vout.size(); i++) {
# # ]
1245 [ # # # # ]: 0 : for (auto range = mapTxSpends.equal_range(COutPoint(parent_wtx.GetTx()->GetHash(), i)); range.first != range.second; range.first++) {
1246 [ # # ]: 0 : const Txid& sibling_txid = range.first->second;
1247 : : // Skip the child_tx itself
1248 [ # # ]: 0 : if (sibling_txid == child_txid) continue;
1249 [ # # ]: 0 : RecursiveUpdateTxState(/*batch=*/nullptr, sibling_txid, [&child_txid, add_conflict](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1250 [ # # # # ]: 0 : return add_conflict ? (wtx.mempool_conflicts.insert(child_txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED)
1251 [ # # ]: 0 : : (wtx.mempool_conflicts.erase(child_txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED);
1252 : : });
1253 : : }
1254 : : }
1255 : 0 : }
1256 : :
1257 : 0 : void CWallet::MarkInputsDirty(const CTransactionRef& tx)
1258 : : {
1259 [ # # ]: 0 : for (const CTxIn& txin : tx->vin) {
1260 : 0 : auto it = mapWallet.find(txin.prevout.hash);
1261 [ # # ]: 0 : if (it != mapWallet.end()) {
1262 : 0 : it->second.MarkDirty();
1263 : : }
1264 : : }
1265 : 0 : }
1266 : :
1267 : 0 : bool CWallet::AbandonTransaction(const Txid& hashTx)
1268 : : {
1269 : 0 : LOCK(cs_wallet);
1270 : 0 : auto it = mapWallet.find(hashTx);
1271 [ # # ]: 0 : assert(it != mapWallet.end());
1272 [ # # # # ]: 0 : return AbandonTransaction(it->second);
1273 : 0 : }
1274 : :
1275 : 0 : bool CWallet::AbandonTransaction(CWalletTx& tx)
1276 : : {
1277 : : // Can't mark abandoned if confirmed or in mempool
1278 [ # # # # ]: 0 : if (GetTxDepthInMainChain(tx) != 0 || tx.InMempool()) {
1279 : 0 : return false;
1280 : : }
1281 : :
1282 : 0 : auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1283 : : // If the orig tx was not in block/mempool, none of its spends can be.
1284 [ # # ]: 0 : assert(!wtx.isConfirmed());
1285 [ # # ]: 0 : assert(!wtx.InMempool());
1286 : : // If already conflicted or abandoned, no need to set abandoned
1287 [ # # # # ]: 0 : if (!wtx.isBlockConflicted() && !wtx.isAbandoned()) {
1288 [ # # ]: 0 : wtx.m_state = TxStateInactive{/*abandoned=*/true};
1289 : 0 : return TxUpdate::NOTIFY_CHANGED;
1290 : : }
1291 : : return TxUpdate::UNCHANGED;
1292 : : };
1293 : :
1294 : : // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1295 : : // States are not permanent, so these transactions can become unabandoned if they are re-added to the
1296 : : // mempool, or confirmed in a block, or conflicted.
1297 : : // Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1298 : : // states change will remain abandoned and will require manual broadcast if the user wants them.
1299 : :
1300 [ # # # # ]: 0 : RecursiveUpdateTxState(tx.GetHash(), try_updating_state);
1301 : :
1302 : 0 : return true;
1303 : : }
1304 : :
1305 : 0 : void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx)
1306 : : {
1307 : 0 : LOCK(cs_wallet);
1308 : :
1309 : : // If number of conflict confirms cannot be determined, this means
1310 : : // that the block is still unknown or not yet part of the main chain,
1311 : : // for example when loading the wallet during a reindex. Do nothing in that
1312 : : // case.
1313 [ # # # # ]: 0 : if (m_last_block_processed_height < 0 || conflicting_height < 0) {
1314 : : return;
1315 : : }
1316 : 0 : int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1317 [ # # ]: 0 : if (conflictconfirms >= 0)
1318 : : return;
1319 : :
1320 : 0 : auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1321 [ # # ]: 0 : if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
1322 : : // Block is 'more conflicted' than current confirm; update.
1323 : : // Mark transaction as conflicted with this block.
1324 : 0 : wtx.m_state = TxStateBlockConflicted{hashBlock, conflicting_height};
1325 : 0 : return TxUpdate::CHANGED;
1326 : : }
1327 : : return TxUpdate::UNCHANGED;
1328 : 0 : };
1329 : :
1330 : : // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
1331 [ # # # # : 0 : RecursiveUpdateTxState(hashTx, try_updating_state);
# # ]
1332 : :
1333 : 0 : }
1334 : :
1335 : 0 : void CWallet::RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
1336 : 0 : WalletBatch batch(GetDatabase());
1337 [ # # ]: 0 : RecursiveUpdateTxState(&batch, tx_hash, try_updating_state);
1338 : 0 : }
1339 : :
1340 : 0 : void CWallet::RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
1341 [ # # ]: 0 : std::set<Txid> todo;
1342 : 0 : std::set<Txid> done;
1343 : :
1344 [ # # ]: 0 : todo.insert(tx_hash);
1345 : :
1346 [ # # ]: 0 : while (!todo.empty()) {
1347 : 0 : Txid now = *todo.begin();
1348 : 0 : todo.erase(now);
1349 [ # # ]: 0 : done.insert(now);
1350 : 0 : auto it = mapWallet.find(now);
1351 [ # # ]: 0 : assert(it != mapWallet.end());
1352 [ # # ]: 0 : CWalletTx& wtx = it->second;
1353 : :
1354 [ # # ]: 0 : TxUpdate update_state = try_updating_state(wtx);
1355 [ # # ]: 0 : if (update_state != TxUpdate::UNCHANGED) {
1356 : 0 : wtx.MarkDirty();
1357 [ # # # # ]: 0 : if (batch) batch->WriteTxMetadata(wtx);
1358 : : // Iterate over all its outputs, and update those tx states as well (if applicable)
1359 [ # # # # : 0 : for (unsigned int i = 0; i < wtx.GetTx()->vout.size(); ++i) {
# # # # ]
1360 : 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
1361 [ # # ]: 0 : for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
1362 [ # # ]: 0 : if (!done.contains(iter->second)) {
1363 [ # # ]: 0 : todo.insert(iter->second);
1364 : : }
1365 : : }
1366 : : }
1367 : :
1368 [ # # ]: 0 : if (update_state == TxUpdate::NOTIFY_CHANGED) {
1369 [ # # # # ]: 0 : NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1370 : : }
1371 : :
1372 : : // If a transaction changes its tx state, that usually changes the balance
1373 : : // available of the outputs it spends. So force those to be recomputed
1374 [ # # # # ]: 0 : MarkInputsDirty(wtx.GetTx());
1375 : : }
1376 : : }
1377 : 0 : }
1378 : :
1379 : 0 : bool CWallet::SyncTransaction(const CTransactionRef& ptx, const SyncTxState& state, bool rescanning_old_block)
1380 : : {
1381 [ # # ]: 0 : if (!AddToWalletIfInvolvingMe(ptx, state, rescanning_old_block))
1382 : : return false; // Not one of ours
1383 : :
1384 : : // If a transaction changes 'conflicted' state, that changes the balance
1385 : : // available of the outputs it spends. So force those to be
1386 : : // recomputed, also:
1387 : 0 : MarkInputsDirty(ptx);
1388 : 0 : return true;
1389 : : }
1390 : :
1391 : 0 : void CWallet::transactionAddedToMempool(const CTransactionRef& tx) {
1392 : 0 : LOCK(cs_wallet);
1393 [ # # ]: 0 : SyncTransaction(tx, TxStateInMempool{});
1394 : :
1395 : 0 : auto it = mapWallet.find(tx->GetHash());
1396 [ # # ]: 0 : if (it != mapWallet.end()) {
1397 [ # # ]: 0 : RefreshMempoolStatus(it->second, chain());
1398 : : }
1399 : :
1400 : 0 : const Txid& txid = tx->GetHash();
1401 : :
1402 [ # # ]: 0 : for (const CTxIn& tx_in : tx->vin) {
1403 : : // For each wallet transaction spending this prevout..
1404 [ # # ]: 0 : for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
1405 [ # # ]: 0 : const Txid& spent_id = range.first->second;
1406 : : // Skip the recently added tx
1407 [ # # ]: 0 : if (spent_id == txid) continue;
1408 [ # # ]: 0 : RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1409 [ # # ]: 0 : return wtx.mempool_conflicts.insert(txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
1410 : : });
1411 : : }
1412 : :
1413 : : }
1414 : :
1415 [ # # ]: 0 : if (tx->version == TRUC_VERSION) {
1416 : : // Unconfirmed TRUC transactions are only allowed a 1-parent-1-child topology.
1417 : : // For any unconfirmed v3 parents (there should be a maximum of 1 except in reorgs),
1418 : : // record this child so the wallet doesn't try to spend any other outputs
1419 [ # # ]: 0 : for (const CTxIn& tx_in : tx->vin) {
1420 : 0 : auto parent_it = mapWallet.find(tx_in.prevout.hash);
1421 [ # # ]: 0 : if (parent_it != mapWallet.end()) {
1422 [ # # ]: 0 : CWalletTx& parent_wtx = parent_it->second;
1423 [ # # ]: 0 : if (parent_wtx.isUnconfirmed()) {
1424 [ # # ]: 0 : parent_wtx.truc_child_in_mempool = tx->GetHash();
1425 : : // Even though these siblings do not spend the same utxos, they can't
1426 : : // be present in the mempool at the same time because of TRUC policy rules
1427 [ # # ]: 0 : UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/true);
1428 : : }
1429 : : }
1430 : : }
1431 : : }
1432 : 0 : }
1433 : :
1434 : 0 : void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {
1435 : 0 : LOCK(cs_wallet);
1436 : 0 : auto it = mapWallet.find(tx->GetHash());
1437 [ # # ]: 0 : if (it != mapWallet.end()) {
1438 [ # # ]: 0 : RefreshMempoolStatus(it->second, chain());
1439 : : }
1440 : : // Handle transactions that were removed from the mempool because they
1441 : : // conflict with transactions in a newly connected block.
1442 [ # # ]: 0 : if (reason == MemPoolRemovalReason::CONFLICT) {
1443 : : // Trigger external -walletnotify notifications for these transactions.
1444 : : // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
1445 : : //
1446 : : // 1. The transactionRemovedFromMempool callback does not currently
1447 : : // provide the conflicting block's hash and height, and for backwards
1448 : : // compatibility reasons it may not be not safe to store conflicted
1449 : : // wallet transactions with a null block hash. See
1450 : : // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1451 : : // 2. For most of these transactions, the wallet's internal conflict
1452 : : // detection in the blockConnected handler will subsequently call
1453 : : // MarkConflicted and update them with CONFLICTED status anyway. This
1454 : : // applies to any wallet transaction that has inputs spent in the
1455 : : // block, or that has ancestors in the wallet with inputs spent by
1456 : : // the block.
1457 : : // 3. Longstanding behavior since the sync implementation in
1458 : : // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1459 : : // implementation before that was to mark these transactions
1460 : : // unconfirmed rather than conflicted.
1461 : : //
1462 : : // Nothing described above should be seen as an unchangeable requirement
1463 : : // when improving this code in the future. The wallet's heuristics for
1464 : : // distinguishing between conflicted and unconfirmed transactions are
1465 : : // imperfect, and could be improved in general, see
1466 : : // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1467 [ # # ]: 0 : SyncTransaction(tx, TxStateInactive{});
1468 : : }
1469 : :
1470 : 0 : const Txid& txid = tx->GetHash();
1471 : :
1472 [ # # ]: 0 : for (const CTxIn& tx_in : tx->vin) {
1473 : : // Iterate over all wallet transactions spending txin.prev
1474 : : // and recursively mark them as no longer conflicting with
1475 : : // txid
1476 [ # # ]: 0 : for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
1477 [ # # ]: 0 : const Txid& spent_id = range.first->second;
1478 : :
1479 [ # # ]: 0 : RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1480 [ # # ]: 0 : return wtx.mempool_conflicts.erase(txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
1481 : : });
1482 : : }
1483 : : }
1484 : :
1485 [ # # ]: 0 : if (tx->version == TRUC_VERSION) {
1486 : : // If this tx has a parent, unset its truc_child_in_mempool to make it possible
1487 : : // to spend from the parent again. If this tx was replaced by another
1488 : : // child of the same parent, transactionAddedToMempool
1489 : : // will update truc_child_in_mempool
1490 [ # # ]: 0 : for (const CTxIn& tx_in : tx->vin) {
1491 : 0 : auto parent_it = mapWallet.find(tx_in.prevout.hash);
1492 [ # # ]: 0 : if (parent_it != mapWallet.end()) {
1493 [ # # ]: 0 : CWalletTx& parent_wtx = parent_it->second;
1494 [ # # ]: 0 : if (parent_wtx.truc_child_in_mempool == tx->GetHash()) {
1495 [ # # ]: 0 : parent_wtx.truc_child_in_mempool = std::nullopt;
1496 [ # # ]: 0 : UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/false);
1497 : : }
1498 : : }
1499 : : }
1500 : : }
1501 : 0 : }
1502 : :
1503 : 0 : void CWallet::blockConnected(const ChainstateRole& role, const interfaces::BlockInfo& block)
1504 : : {
1505 [ # # ]: 0 : if (role.historical) {
1506 : : return;
1507 : : }
1508 [ # # ]: 0 : assert(block.data);
1509 : 0 : LOCK(cs_wallet);
1510 : :
1511 : : // Update the best block in memory first. This will set the best block's height, which is
1512 : : // needed by MarkConflicted.
1513 [ # # ]: 0 : SetLastBlockProcessedInMem(block.height, block.hash);
1514 : :
1515 : : // No need to scan block if it was created before the wallet birthday.
1516 : : // Uses chain max time and twice the grace period to adjust time for block time variability.
1517 [ # # # # ]: 0 : if (block.chain_time_max < m_birth_time.load() - (TIMESTAMP_WINDOW * 2)) return;
1518 : :
1519 : : // Scan block
1520 : : bool wallet_updated = false;
1521 [ # # # # ]: 0 : for (size_t index = 0; index < block.data->vtx.size(); index++) {
1522 [ # # ]: 0 : wallet_updated |= SyncTransaction(block.data->vtx[index], TxStateConfirmed{block.hash, block.height, static_cast<int>(index)});
1523 [ # # ]: 0 : transactionRemovedFromMempool(block.data->vtx[index], MemPoolRemovalReason::BLOCK);
1524 : : }
1525 : :
1526 : : // Update on disk if this block resulted in us updating a tx, or periodically every 144 blocks (~1 day)
1527 [ # # # # ]: 0 : if (wallet_updated || block.height % 144 == 0) {
1528 [ # # ]: 0 : WriteBestBlock();
1529 : : }
1530 : 0 : }
1531 : :
1532 : 0 : void CWallet::blockDisconnected(const interfaces::BlockInfo& block)
1533 : : {
1534 [ # # ]: 0 : assert(block.data);
1535 : 0 : LOCK(cs_wallet);
1536 : :
1537 : : // At block disconnection, this will change an abandoned transaction to
1538 : : // be unconfirmed, whether or not the transaction is added back to the mempool.
1539 : : // User may have to call abandontransaction again. It may be addressed in the
1540 : : // future with a stickier abandoned state or even removing abandontransaction call.
1541 : 0 : int disconnect_height = block.height;
1542 : :
1543 [ # # # # ]: 0 : for (size_t index = 0; index < block.data->vtx.size(); index++) {
1544 [ # # ]: 0 : const CTransactionRef& ptx = block.data->vtx[index];
1545 : : // Coinbase transactions are not only inactive but also abandoned,
1546 : : // meaning they should never be relayed standalone via the p2p protocol.
1547 [ # # ]: 0 : SyncTransaction(ptx, TxStateInactive{/*abandoned=*/index == 0});
1548 : :
1549 [ # # ]: 0 : for (const CTxIn& tx_in : ptx->vin) {
1550 : : // No other wallet transactions conflicted with this transaction
1551 [ # # ]: 0 : if (!mapTxSpends.contains(tx_in.prevout)) continue;
1552 : :
1553 : 0 : std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
1554 : :
1555 : : // For all of the spends that conflict with this transaction
1556 [ # # ]: 0 : for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
1557 [ # # ]: 0 : CWalletTx& wtx = mapWallet.find(_it->second)->second;
1558 : :
1559 [ # # ]: 0 : if (!wtx.isBlockConflicted()) continue;
1560 : :
1561 : 0 : auto try_updating_state = [&](CWalletTx& tx) {
1562 [ # # ]: 0 : if (!tx.isBlockConflicted()) return TxUpdate::UNCHANGED;
1563 [ # # ]: 0 : if (tx.state<TxStateBlockConflicted>()->conflicting_block_height >= disconnect_height) {
1564 [ # # ]: 0 : tx.m_state = TxStateInactive{};
1565 : 0 : return TxUpdate::CHANGED;
1566 : : }
1567 : : return TxUpdate::UNCHANGED;
1568 : 0 : };
1569 : :
1570 [ # # # # ]: 0 : RecursiveUpdateTxState(wtx.GetTx()->GetHash(), try_updating_state);
1571 : : }
1572 : : }
1573 : : }
1574 : :
1575 : : // Update the best block
1576 [ # # # # ]: 0 : SetLastBlockProcessed(block.height - 1, *Assert(block.prev_hash));
1577 : 0 : }
1578 : :
1579 : 0 : void CWallet::updatedBlockTip()
1580 : : {
1581 : 0 : m_best_block_time = GetTime();
1582 : 0 : }
1583 : :
1584 : 0 : void CWallet::BlockUntilSyncedToCurrentChain() const {
1585 : 0 : AssertLockNotHeld(cs_wallet);
1586 : : // Skip the queue-draining stuff if we know we're caught up with
1587 : : // chain().Tip(), otherwise put a callback in the validation interface queue and wait
1588 : : // for the queue to drain enough to execute it (indicating we are caught up
1589 : : // at least with the time we entered this function).
1590 [ # # ]: 0 : uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1591 : 0 : chain().waitForNotificationsIfTipChanged(last_block_hash);
1592 : 0 : }
1593 : :
1594 : : // Note that this function doesn't distinguish between a 0-valued input,
1595 : : // and a not-"is mine" input.
1596 : 0 : CAmount CWallet::GetDebit(const CTxIn &txin) const
1597 : : {
1598 : 0 : LOCK(cs_wallet);
1599 [ # # ]: 0 : auto txo = GetTXO(txin.prevout);
1600 [ # # ]: 0 : if (txo) {
1601 : 0 : return txo->GetTxOut().nValue;
1602 : : }
1603 : : return 0;
1604 : 0 : }
1605 : :
1606 : 412565 : bool CWallet::IsMine(const CTxOut& txout) const
1607 : : {
1608 : 412565 : AssertLockHeld(cs_wallet);
1609 : 412565 : return IsMine(txout.scriptPubKey);
1610 : : }
1611 : :
1612 : 2640 : bool CWallet::IsMine(const CTxDestination& dest) const
1613 : : {
1614 : 2640 : AssertLockHeld(cs_wallet);
1615 [ + - ]: 2640 : return IsMine(GetScriptForDestination(dest));
1616 : : }
1617 : :
1618 : 415205 : bool CWallet::IsMine(const CScript& script) const
1619 : : {
1620 : 415205 : AssertLockHeld(cs_wallet);
1621 : :
1622 : : // Search the cache so that IsMine is called only on the relevant SPKMs instead of on everything in m_spk_managers
1623 : 415205 : const auto& it = m_cached_spks.find(script);
1624 [ + - ]: 415205 : if (it != m_cached_spks.end()) {
1625 : 415205 : bool res = false;
1626 [ + + ]: 830497 : for (const auto& spkm : it->second) {
1627 [ + + + - ]: 830497 : res = res || spkm->IsMine(script);
1628 : : }
1629 : 415205 : Assume(res);
1630 : 415205 : return res;
1631 : : }
1632 : :
1633 : : return false;
1634 : : }
1635 : :
1636 : 0 : bool CWallet::IsMine(const CTransaction& tx) const
1637 : : {
1638 : 0 : AssertLockHeld(cs_wallet);
1639 [ # # ]: 0 : for (const CTxOut& txout : tx.vout)
1640 [ # # ]: 0 : if (IsMine(txout))
1641 : : return true;
1642 : : return false;
1643 : : }
1644 : :
1645 : 0 : bool CWallet::IsMine(const COutPoint& outpoint) const
1646 : : {
1647 : 0 : AssertLockHeld(cs_wallet);
1648 : 0 : auto wtx = GetWalletTx(outpoint.hash);
1649 [ # # ]: 0 : if (!wtx) {
1650 : : return false;
1651 : : }
1652 [ # # # # : 0 : if (outpoint.n >= wtx->GetTx()->vout.size()) {
# # ]
1653 : : return false;
1654 : : }
1655 [ # # # # ]: 0 : return IsMine(wtx->GetTx()->vout[outpoint.n]);
1656 : : }
1657 : :
1658 : 244685 : bool CWallet::IsFromMe(const CTransaction& tx) const
1659 : : {
1660 : 244685 : LOCK(cs_wallet);
1661 [ - + ]: 244685 : for (const CTxIn& txin : tx.vin) {
1662 [ # # # # ]: 0 : if (GetTXO(txin.prevout)) return true;
1663 : : }
1664 : : return false;
1665 : 244685 : }
1666 : :
1667 : 0 : CAmount CWallet::GetDebit(const CTransaction& tx) const
1668 : : {
1669 : 0 : CAmount nDebit = 0;
1670 [ # # ]: 0 : for (const CTxIn& txin : tx.vin)
1671 : : {
1672 : 0 : nDebit += GetDebit(txin);
1673 [ # # ]: 0 : if (!MoneyRange(nDebit))
1674 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
1675 : : }
1676 : 0 : return nDebit;
1677 : : }
1678 : :
1679 : 0 : bool CWallet::IsHDEnabled() const
1680 : : {
1681 : : // All Active ScriptPubKeyMans must be HD for this to be true
1682 : 0 : bool result = false;
1683 [ # # ]: 0 : for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
1684 [ # # # # ]: 0 : if (!spk_man->IsHDEnabled()) return false;
1685 : 0 : result = true;
1686 : : }
1687 : 0 : return result;
1688 : : }
1689 : :
1690 : 0 : bool CWallet::CanGetAddresses(bool internal) const
1691 : : {
1692 : 0 : LOCK(cs_wallet);
1693 [ # # ]: 0 : if (m_spk_managers.empty()) return false;
1694 [ # # ]: 0 : for (OutputType t : OUTPUT_TYPES) {
1695 [ # # ]: 0 : auto spk_man = GetScriptPubKeyMan(t, internal);
1696 [ # # # # : 0 : if (spk_man && spk_man->CanGetAddresses(internal)) {
# # ]
1697 : : return true;
1698 : : }
1699 : : }
1700 : : return false;
1701 : 0 : }
1702 : :
1703 : 9784 : void CWallet::SetWalletFlag(uint64_t flags)
1704 : : {
1705 : 9784 : WalletBatch batch(GetDatabase());
1706 [ + - ]: 9784 : return SetWalletFlagWithDB(batch, flags);
1707 : 9784 : }
1708 : :
1709 : 9784 : void CWallet::SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags)
1710 : : {
1711 : 9784 : LOCK(cs_wallet);
1712 [ + - ]: 9784 : m_wallet_flags |= flags;
1713 [ + - - + ]: 9784 : if (!batch.WriteWalletFlags(m_wallet_flags))
1714 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1715 : 9784 : }
1716 : :
1717 : 1732 : void CWallet::UnsetWalletFlag(uint64_t flag)
1718 : : {
1719 : 1732 : WalletBatch batch(GetDatabase());
1720 [ + - ]: 1732 : UnsetWalletFlagWithDB(batch, flag);
1721 : 1732 : }
1722 : :
1723 : 1732 : void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
1724 : : {
1725 : 1732 : LOCK(cs_wallet);
1726 [ + - ]: 1732 : m_wallet_flags &= ~flag;
1727 [ + - - + ]: 1732 : if (!batch.WriteWalletFlags(m_wallet_flags))
1728 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1729 : 1732 : }
1730 : :
1731 : 0 : void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
1732 : : {
1733 : 0 : UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
1734 : 0 : }
1735 : :
1736 : 151990 : bool CWallet::IsWalletFlagSet(uint64_t flag) const
1737 : : {
1738 : 151990 : return (m_wallet_flags & flag);
1739 : : }
1740 : :
1741 : 0 : bool CWallet::LoadWalletFlags(uint64_t flags)
1742 : : {
1743 : 0 : LOCK(cs_wallet);
1744 [ # # ]: 0 : if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1745 : : // contains unknown non-tolerable wallet flags
1746 : : return false;
1747 : : }
1748 : 0 : m_wallet_flags = flags;
1749 : :
1750 : 0 : return true;
1751 : 0 : }
1752 : :
1753 : 0 : void CWallet::InitWalletFlags(uint64_t flags)
1754 : : {
1755 : 0 : LOCK(cs_wallet);
1756 : :
1757 : : // We should never be writing unknown non-tolerable wallet flags
1758 [ # # ]: 0 : assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1759 : : // This should only be used once, when creating a new wallet - so current flags are expected to be blank
1760 [ # # ]: 0 : assert(m_wallet_flags == 0);
1761 : :
1762 [ # # # # : 0 : if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
# # ]
1763 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1764 : : }
1765 : :
1766 [ # # # # ]: 0 : Assert(LoadWalletFlags(flags));
1767 : 0 : }
1768 : :
1769 : 0 : uint64_t CWallet::GetWalletFlags() const
1770 : : {
1771 : 0 : return m_wallet_flags;
1772 : : }
1773 : :
1774 : 9823 : void CWallet::MaybeUpdateBirthTime(int64_t time)
1775 : : {
1776 [ + + ]: 9823 : int64_t birthtime = m_birth_time.load();
1777 [ + + ]: 9823 : if (time < birthtime) {
1778 : 9809 : m_birth_time = time;
1779 : : }
1780 : 9823 : }
1781 : :
1782 : 0 : bool CWallet::SubmitTxMemoryPoolAndRelay(CWalletTx& wtx,
1783 : : std::string& err_string,
1784 : : node::TxBroadcast broadcast_method) const
1785 : : {
1786 : 0 : AssertLockHeld(cs_wallet);
1787 : :
1788 : : // Can't relay if wallet is not broadcasting
1789 [ # # ]: 0 : if (!GetBroadcastTransactions()) return false;
1790 : : // Don't relay abandoned transactions
1791 [ # # ]: 0 : if (wtx.isAbandoned()) return false;
1792 : : // Don't try to submit coinbase transactions. These would fail anyway but would
1793 : : // cause log spam.
1794 [ # # ]: 0 : if (wtx.IsCoinBase()) return false;
1795 : : // Don't try to submit conflicted or confirmed transactions.
1796 [ # # ]: 0 : if (GetTxDepthInMainChain(wtx) != 0) return false;
1797 : :
1798 : 0 : const char* what{""};
1799 [ # # # # ]: 0 : switch (broadcast_method) {
1800 : 0 : case node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL:
1801 : 0 : what = "to mempool and for broadcast to peers";
1802 : 0 : break;
1803 : 0 : case node::TxBroadcast::MEMPOOL_NO_BROADCAST:
1804 : 0 : what = "to mempool without broadcast";
1805 : 0 : break;
1806 : 0 : case node::TxBroadcast::NO_MEMPOOL_PRIVATE_BROADCAST:
1807 : 0 : what = "for private broadcast without adding to the mempool";
1808 : 0 : break;
1809 : : }
1810 [ # # ]: 0 : WalletLogPrintf("Submitting wtx %s %s", wtx.GetHash().ToString(), what);
1811 : : // We must set TxStateInMempool here. Even though it will also be set later by the
1812 : : // entered-mempool callback, if we did not there would be a race where a
1813 : : // user could call sendmoney in a loop and hit spurious out of funds errors
1814 : : // because we think that this newly generated transaction's change is
1815 : : // unavailable as we're not yet aware that it is in the mempool.
1816 : : //
1817 : : // If broadcast fails for any reason, trying to set wtx.m_state here would be incorrect.
1818 : : // If transaction was previously in the mempool, it should be updated when
1819 : : // TransactionRemovedFromMempool fires.
1820 [ # # # # ]: 0 : bool ret = chain().broadcastTransaction(wtx.GetTx(), m_max_tx_fee, m_max_tx_fee_rate, broadcast_method, err_string);
1821 [ # # # # ]: 0 : if (ret) wtx.m_state = TxStateInMempool{};
1822 : : return ret;
1823 : : }
1824 : :
1825 : 0 : std::set<Txid> CWallet::GetTxConflicts(const CWalletTx& wtx) const
1826 : : {
1827 : 0 : AssertLockHeld(cs_wallet);
1828 : :
1829 : 0 : const Txid myHash{wtx.GetHash()};
1830 : 0 : std::set<Txid> result{GetConflicts(myHash)};
1831 : 0 : result.erase(myHash);
1832 : 0 : return result;
1833 : : }
1834 : :
1835 : 0 : bool CWallet::ShouldResend() const
1836 : : {
1837 : : // Don't attempt to resubmit if the wallet is configured to not broadcast
1838 [ # # ]: 0 : if (!fBroadcastTransactions) return false;
1839 : :
1840 : : // During reindex, importing and IBD, old wallet transactions become
1841 : : // unconfirmed. Don't resend them as that would spam other nodes.
1842 : : // We only allow forcing mempool submission when not relaying to avoid this spam.
1843 [ # # ]: 0 : if (!chain().isReadyToBroadcast()) return false;
1844 : :
1845 : : // Do this infrequently and randomly to avoid giving away
1846 : : // that these are our transactions.
1847 [ # # ]: 0 : if (NodeClock::now() < m_next_resend) return false;
1848 : :
1849 : : return true;
1850 : : }
1851 : :
1852 : 11691 : NodeClock::time_point CWallet::GetDefaultNextResend() { return FastRandomContext{}.rand_uniform_delay(NodeClock::now() + 12h, 24h); }
1853 : :
1854 : : // Resubmit transactions from the wallet to the mempool, optionally asking the
1855 : : // mempool to relay them. On startup, we will do this for all unconfirmed
1856 : : // transactions but will not ask the mempool to relay them. We do this on startup
1857 : : // to ensure that our own mempool is aware of our transactions. There
1858 : : // is a privacy side effect here as not broadcasting on startup also means that we won't
1859 : : // inform the world of our wallet's state, particularly if the wallet (or node) is not
1860 : : // yet synced.
1861 : : //
1862 : : // Otherwise this function is called periodically in order to relay our unconfirmed txs.
1863 : : // We do this on a random timer to slightly obfuscate which transactions
1864 : : // come from our wallet.
1865 : : //
1866 : : // TODO: Ideally, we'd only resend transactions that we think should have been
1867 : : // mined in the most recent block. Any transaction that wasn't in the top
1868 : : // blockweight of transactions in the mempool shouldn't have been mined,
1869 : : // and so is probably just sitting in the mempool waiting to be confirmed.
1870 : : // Rebroadcasting does nothing to speed up confirmation and only damages
1871 : : // privacy.
1872 : : //
1873 : : // The `force` option results in all unconfirmed transactions being submitted to
1874 : : // the mempool. This does not necessarily result in those transactions being relayed,
1875 : : // that depends on the `broadcast_method` option. Periodic rebroadcast uses the pattern
1876 : : // broadcast_method=TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL force=false, while loading into
1877 : : // the mempool (on start, or after import) uses
1878 : : // broadcast_method=TxBroadcast::MEMPOOL_NO_BROADCAST force=true.
1879 : 0 : void CWallet::ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force)
1880 : : {
1881 : : // Don't attempt to resubmit if the wallet is configured to not broadcast,
1882 : : // even if forcing.
1883 [ # # ]: 0 : if (!fBroadcastTransactions) return;
1884 : :
1885 : 0 : int submitted_tx_count = 0;
1886 : :
1887 : 0 : { // cs_wallet scope
1888 : 0 : LOCK(cs_wallet);
1889 : :
1890 : : // First filter for the transactions we want to rebroadcast.
1891 : : // We use a set with WalletTxOrderComparator so that rebroadcasting occurs in insertion order
1892 : 0 : std::set<CWalletTx*, WalletTxOrderComparator> to_submit;
1893 [ # # # # ]: 0 : for (auto& [txid, wtx] : mapWallet) {
1894 : : // Only rebroadcast unconfirmed txs
1895 [ # # ]: 0 : if (!wtx.isUnconfirmed()) continue;
1896 : :
1897 : : // Attempt to rebroadcast all txes more than 5 minutes older than
1898 : : // the last block, or all txs if forcing.
1899 [ # # # # ]: 0 : if (!force && wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
1900 [ # # ]: 0 : to_submit.insert(&wtx);
1901 : : }
1902 : : // Now try submitting the transactions to the memory pool and (optionally) relay them.
1903 [ # # ]: 0 : for (auto wtx : to_submit) {
1904 [ # # ]: 0 : std::string unused_err_string;
1905 [ # # # # ]: 0 : if (SubmitTxMemoryPoolAndRelay(*wtx, unused_err_string, broadcast_method)) ++submitted_tx_count;
1906 : 0 : }
1907 [ # # ]: 0 : } // cs_wallet
1908 : :
1909 [ # # ]: 0 : if (submitted_tx_count > 0) {
1910 : 0 : WalletLogPrintf("%s: resubmit %u unconfirmed transactions", __func__, submitted_tx_count);
1911 : : }
1912 : : }
1913 : :
1914 : : /** @} */ // end of mapWallet
1915 : :
1916 : 0 : void MaybeResendWalletTxs(WalletContext& context)
1917 : : {
1918 [ # # ]: 0 : for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
1919 [ # # # # ]: 0 : if (!pwallet->ShouldResend()) continue;
1920 [ # # ]: 0 : pwallet->ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*force=*/false);
1921 [ # # ]: 0 : pwallet->SetNextResend();
1922 : : }
1923 : 0 : }
1924 : :
1925 : :
1926 : 1506 : bool CWallet::SignTransaction(CMutableTransaction& tx) const
1927 : : {
1928 : 1506 : AssertLockHeld(cs_wallet);
1929 : :
1930 : : // Build coins map
1931 : 1506 : std::map<COutPoint, Coin> coins;
1932 [ + + ]: 107224 : for (auto& input : tx.vin) {
1933 : 105718 : const auto mi = mapWallet.find(input.prevout.hash);
1934 [ + - + - : 211436 : if(mi == mapWallet.end() || input.prevout.n >= mi->second.GetTx()->vout.size()) {
- + + - +
- ]
1935 : : return false;
1936 : : }
1937 [ + - ]: 105718 : const CWalletTx& wtx = mi->second;
1938 [ + - ]: 105718 : int prev_height = wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height : 0;
1939 [ + - + - : 211436 : coins[input.prevout] = Coin(wtx.GetTx()->vout[input.prevout.n], prev_height, wtx.IsCoinBase());
+ - + - ]
1940 : : }
1941 [ + - ]: 1506 : std::map<int, bilingual_str> input_errors;
1942 [ + - ]: 1506 : return SignTransaction(tx, coins, SIGHASH_DEFAULT, input_errors);
1943 : 3012 : }
1944 : :
1945 : 1506 : bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1946 : : {
1947 : : // Try to sign with all ScriptPubKeyMans
1948 [ + - ]: 7316 : for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
1949 : : // spk_man->SignTransaction will return true if the transaction is complete,
1950 : : // so we can exit early and return true if that happens
1951 [ + - + + ]: 7316 : if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
1952 : 1506 : return true;
1953 : : }
1954 : : }
1955 : :
1956 : : // At this point, one input was not fully signed otherwise we would have exited already
1957 : 0 : return false;
1958 : : }
1959 : :
1960 : 0 : std::optional<PSBTError> CWallet::FillPSBT(PartiallySignedTransaction& psbtx, const common::PSBTFillOptions& options, bool& complete, size_t* n_signed) const
1961 : : {
1962 [ # # ]: 0 : if (n_signed) {
1963 : 0 : *n_signed = 0;
1964 : : }
1965 : 0 : LOCK(cs_wallet);
1966 : : // Get all of the previous transactions
1967 [ # # ]: 0 : for (PSBTInput& input : psbtx.inputs) {
1968 [ # # # # ]: 0 : if (PSBTInputSigned(input)) {
1969 : 0 : continue;
1970 : : }
1971 : :
1972 : : // If we have no utxo, grab it from the wallet.
1973 [ # # ]: 0 : if (!input.non_witness_utxo) {
1974 : 0 : const Txid& txhash = input.prev_txid;
1975 : 0 : const auto it = mapWallet.find(txhash);
1976 [ # # ]: 0 : if (it != mapWallet.end()) {
1977 [ # # ]: 0 : const CWalletTx& wtx = it->second;
1978 : : // We only need the non_witness_utxo, which is a superset of the witness_utxo.
1979 : : // The signing code will switch to the smaller witness_utxo if this is ok.
1980 [ # # # # ]: 0 : input.non_witness_utxo = wtx.GetTx();
1981 : : }
1982 : : }
1983 : : }
1984 : :
1985 [ # # ]: 0 : std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
1986 [ # # ]: 0 : if (!txdata_res) {
1987 : 0 : return PSBTError::INVALID_TX;
1988 : : }
1989 [ # # ]: 0 : const PrecomputedTransactionData& txdata = *txdata_res;
1990 : :
1991 : : // Fill in information from ScriptPubKeyMans
1992 [ # # # # ]: 0 : for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
1993 : 0 : int n_signed_this_spkm = 0;
1994 [ # # ]: 0 : const auto error{spk_man->FillPSBT(psbtx, txdata, options, &n_signed_this_spkm)};
1995 [ # # ]: 0 : if (error) {
1996 : 0 : return error;
1997 : : }
1998 : :
1999 [ # # ]: 0 : if (n_signed) {
2000 : 0 : (*n_signed) += n_signed_this_spkm;
2001 : : }
2002 : 0 : }
2003 : :
2004 [ # # ]: 0 : RemoveUnnecessaryTransactions(psbtx);
2005 : :
2006 : : // Complete if every input is now signed
2007 : 0 : complete = true;
2008 [ # # # # ]: 0 : for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
2009 [ # # ]: 0 : complete &= PSBTInputSignedAndVerified(psbtx, i, &txdata);
2010 : : }
2011 : :
2012 : 0 : return {};
2013 [ # # ]: 0 : }
2014 : :
2015 : 0 : SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2016 : : {
2017 : 0 : SignatureData sigdata;
2018 [ # # ]: 0 : CScript script_pub_key = GetScriptForDestination(pkhash);
2019 [ # # ]: 0 : for (const auto& spk_man_pair : m_spk_managers) {
2020 [ # # # # ]: 0 : if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2021 [ # # ]: 0 : LOCK(cs_wallet); // DescriptorScriptPubKeyMan calls IsLocked which can lock cs_wallet in a deadlocking order
2022 [ # # # # ]: 0 : return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2023 : 0 : }
2024 : : }
2025 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2026 : 0 : }
2027 : :
2028 : 2154 : OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
2029 : : {
2030 : : // If -changetype is specified, always use that change type.
2031 [ + + ]: 2154 : if (change_type) {
2032 : 1258 : return *change_type;
2033 : : }
2034 : :
2035 : : // if m_default_address_type is legacy, use legacy address as change.
2036 [ + - ]: 896 : if (m_default_address_type == OutputType::LEGACY) {
2037 : : return OutputType::LEGACY;
2038 : : }
2039 : :
2040 : 896 : bool any_tr{false};
2041 : 896 : bool any_wpkh{false};
2042 : 896 : bool any_sh{false};
2043 : 896 : bool any_pkh{false};
2044 : :
2045 [ + + ]: 11506 : for (const auto& recipient : vecSend) {
2046 [ + - ]: 10610 : if (std::get_if<WitnessV1Taproot>(&recipient.dest)) {
2047 : : any_tr = true;
2048 [ + - ]: 9012 : } else if (std::get_if<WitnessV0KeyHash>(&recipient.dest)) {
2049 : : any_wpkh = true;
2050 [ + - ]: 18547 : } else if (std::get_if<ScriptHash>(&recipient.dest)) {
2051 : : any_sh = true;
2052 [ + - ]: 16139 : } else if (std::get_if<PKHash>(&recipient.dest)) {
2053 : 794 : any_pkh = true;
2054 : : }
2055 : : }
2056 : :
2057 : 896 : const bool has_bech32m_spkman(GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/true));
2058 [ + + ]: 896 : if (has_bech32m_spkman && any_tr) {
2059 : : // Currently tr is the only type supported by the BECH32M spkman
2060 : : return OutputType::BECH32M;
2061 : : }
2062 : 704 : const bool has_bech32_spkman(GetScriptPubKeyMan(OutputType::BECH32, /*internal=*/true));
2063 [ + + ]: 704 : if (has_bech32_spkman && any_wpkh) {
2064 : : // Currently wpkh is the only type supported by the BECH32 spkman
2065 : : return OutputType::BECH32;
2066 : : }
2067 : 613 : const bool has_p2sh_segwit_spkman(GetScriptPubKeyMan(OutputType::P2SH_SEGWIT, /*internal=*/true));
2068 [ + + ]: 613 : if (has_p2sh_segwit_spkman && any_sh) {
2069 : : // Currently sh_wpkh is the only type supported by the P2SH_SEGWIT spkman
2070 : : // As of 2021 about 80% of all SH are wrapping WPKH, so use that
2071 : : return OutputType::P2SH_SEGWIT;
2072 : : }
2073 : 393 : const bool has_legacy_spkman(GetScriptPubKeyMan(OutputType::LEGACY, /*internal=*/true));
2074 [ + + ]: 393 : if (has_legacy_spkman && any_pkh) {
2075 : : // Currently pkh is the only type supported by the LEGACY spkman
2076 : : return OutputType::LEGACY;
2077 : : }
2078 : :
2079 [ - + ]: 313 : if (has_bech32m_spkman) {
2080 : : return OutputType::BECH32M;
2081 : : }
2082 [ # # ]: 0 : if (has_bech32_spkman) {
2083 : : return OutputType::BECH32;
2084 : : }
2085 : : // else use m_default_address_type for change
2086 : 0 : return m_default_address_type;
2087 : : }
2088 : :
2089 : 0 : void CWallet::CommitTransaction(
2090 : : CTransactionRef tx,
2091 : : std::optional<Txid> replaces_txid,
2092 : : std::optional<std::string> comment,
2093 : : std::optional<std::string> comment_to,
2094 : : const std::vector<std::string>& messages,
2095 : : const std::vector<std::string>& payment_requests
2096 : : )
2097 : : {
2098 : 0 : LOCK(cs_wallet);
2099 [ # # # # : 0 : WalletLogPrintf("CommitTransaction:\n%s", util::RemoveSuffixView(tx->ToString(), "\n"));
# # ]
2100 : :
2101 : : // Add tx to wallet, because if it has change it's also ours,
2102 : : // otherwise just for transaction history.
2103 [ # # # # : 0 : CWalletTx* wtx = AddToWallet(tx, TxStateInactive{}, [&](CWalletTx& wtx, bool new_tx) {
# # # # ]
2104 [ # # ]: 0 : if (replaces_txid) wtx.m_replaces_txid = replaces_txid;
2105 [ # # ]: 0 : if (comment) wtx.m_comment = comment;
2106 [ # # ]: 0 : if (comment_to) wtx.m_comment_to = comment_to;
2107 [ # # ]: 0 : if (!messages.empty()) wtx.m_messages = messages;
2108 [ # # ]: 0 : if (!payment_requests.empty()) wtx.m_payment_requests = payment_requests;
2109 : 0 : return true;
2110 : : });
2111 : :
2112 : : // wtx can only be null if the db write failed.
2113 [ # # ]: 0 : if (!wtx) {
2114 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Wallet db error, transaction commit failed");
2115 : : }
2116 : :
2117 : : // Notify that old coins are spent
2118 [ # # ]: 0 : for (const CTxIn& txin : tx->vin) {
2119 [ # # ]: 0 : CWalletTx &coin = mapWallet.at(txin.prevout.hash);
2120 : 0 : coin.MarkDirty();
2121 [ # # # # ]: 0 : NotifyTransactionChanged(coin.GetHash(), CT_UPDATED);
2122 : : }
2123 : :
2124 [ # # ]: 0 : if (!fBroadcastTransactions) {
2125 : : // Don't submit tx to the mempool
2126 [ # # ]: 0 : return;
2127 : : }
2128 : :
2129 [ # # ]: 0 : std::string err_string;
2130 [ # # # # ]: 0 : if (!SubmitTxMemoryPoolAndRelay(*wtx, err_string, node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL)) {
2131 [ # # ]: 0 : WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s", err_string);
2132 : : // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2133 : : }
2134 [ # # ]: 0 : }
2135 : :
2136 : 0 : DBErrors CWallet::PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings)
2137 : : {
2138 : 0 : LOCK(cs_wallet);
2139 : :
2140 [ # # ]: 0 : Assert(m_spk_managers.empty());
2141 [ # # ]: 0 : Assert(m_wallet_flags == 0);
2142 [ # # # # ]: 0 : DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
2143 : :
2144 [ # # ]: 0 : if (m_spk_managers.empty()) {
2145 [ # # ]: 0 : assert(m_external_spk_managers.empty());
2146 [ # # ]: 0 : assert(m_internal_spk_managers.empty());
2147 : : }
2148 : :
2149 [ # # ]: 0 : const auto wallet_file = m_database->Filename();
2150 [ # # # # : 0 : switch (nLoadWalletRet) {
# # # # #
# ]
2151 : : case DBErrors::LOAD_OK:
2152 : : break;
2153 : 0 : case DBErrors::NONCRITICAL_ERROR:
2154 [ # # ]: 0 : warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
2155 : : " or address metadata may be missing or incorrect."),
2156 : : wallet_file));
2157 : 0 : break;
2158 : 0 : case DBErrors::NEED_RESCAN:
2159 [ # # ]: 0 : warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
2160 : : " Rescanning wallet."), wallet_file));
2161 : 0 : break;
2162 : 0 : case DBErrors::CORRUPT:
2163 [ # # ]: 0 : error = strprintf(_("Error loading %s: Wallet corrupted"), wallet_file);
2164 : 0 : break;
2165 : 0 : case DBErrors::TOO_NEW:
2166 [ # # ]: 0 : error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), wallet_file, CLIENT_NAME);
2167 : 0 : break;
2168 : 0 : case DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED:
2169 [ # # ]: 0 : error = strprintf(_("Error loading %s: External signer wallet being loaded without external signer support compiled"), wallet_file);
2170 : 0 : break;
2171 : 0 : case DBErrors::UNKNOWN_DESCRIPTOR:
2172 [ # # ]: 0 : error = strprintf(_("Unrecognized descriptor found. Loading wallet %s\n\n"
2173 : : "The wallet might have been created on a newer version.\n"
2174 : 0 : "Please try running the latest software version.\n"), wallet_file);
2175 : 0 : break;
2176 : 0 : case DBErrors::UNEXPECTED_LEGACY_ENTRY:
2177 [ # # ]: 0 : error = strprintf(_("Unexpected legacy entry in descriptor wallet found. Loading wallet %s\n\n"
2178 : 0 : "The wallet might have been tampered with or created with malicious intent.\n"), wallet_file);
2179 : 0 : break;
2180 : 0 : case DBErrors::LEGACY_WALLET:
2181 [ # # ]: 0 : error = strprintf(_("Error loading %s: Wallet is a legacy wallet. Please migrate to a descriptor wallet using the migration tool (migratewallet RPC)."), wallet_file);
2182 : 0 : break;
2183 : 0 : case DBErrors::LOAD_FAIL:
2184 [ # # ]: 0 : error = strprintf(_("Error loading %s"), wallet_file);
2185 : 0 : break;
2186 : : } // no default case, so the compiler can warn about missing cases
2187 : 0 : return nLoadWalletRet;
2188 [ # # ]: 0 : }
2189 : :
2190 : 0 : util::Result<void> CWallet::RemoveTxs(std::vector<Txid>& txs_to_remove)
2191 : : {
2192 : 0 : AssertLockHeld(cs_wallet);
2193 [ # # ]: 0 : bilingual_str str_err; // future: make RunWithinTxn return a util::Result
2194 [ # # # # ]: 0 : bool was_txn_committed = RunWithinTxn(GetDatabase(), /*process_desc=*/"remove transactions", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
2195 : 0 : util::Result<void> result{RemoveTxs(batch, txs_to_remove)};
2196 [ # # # # ]: 0 : if (!result) str_err = util::ErrorString(result);
2197 : 0 : return result.has_value();
2198 : 0 : });
2199 [ # # # # ]: 0 : if (!str_err.empty()) return util::Error{str_err};
2200 [ # # # # ]: 0 : if (!was_txn_committed) return util::Error{_("Error starting/committing db txn for wallet transactions removal process")};
2201 : 0 : return {}; // all good
2202 : 0 : }
2203 : :
2204 : 0 : util::Result<void> CWallet::RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove)
2205 : : {
2206 : 0 : AssertLockHeld(cs_wallet);
2207 [ # # ]: 0 : if (!batch.HasActiveTxn()) return util::Error{strprintf(_("The transactions removal process can only be executed within a db txn"))};
2208 : :
2209 : : // Check for transaction existence and remove entries from disk
2210 : 0 : std::vector<decltype(mapWallet)::const_iterator> erased_txs;
2211 : 0 : bilingual_str str_err;
2212 [ # # ]: 0 : for (const Txid& hash : txs_to_remove) {
2213 : 0 : auto it_wtx = mapWallet.find(hash);
2214 [ # # ]: 0 : if (it_wtx == mapWallet.end()) {
2215 [ # # # # ]: 0 : return util::Error{strprintf(_("Transaction %s does not belong to this wallet"), hash.GetHex())};
2216 : : }
2217 [ # # # # ]: 0 : if (!batch.EraseTx(hash)) {
2218 [ # # # # ]: 0 : return util::Error{strprintf(_("Failure removing transaction: %s"), hash.GetHex())};
2219 : : }
2220 [ # # ]: 0 : erased_txs.emplace_back(it_wtx);
2221 : : }
2222 : :
2223 : : // Register callback to update the memory state only when the db txn is actually dumped to disk
2224 [ # # # # : 0 : batch.RegisterTxnListener({.on_commit=[&, erased_txs]() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
# # ]
2225 : : // Update the in-memory state and notify upper layers about the removals
2226 [ # # ]: 0 : for (const auto& it : erased_txs) {
2227 : 0 : const Txid hash{it->first};
2228 : 0 : wtxOrdered.erase(it->second.m_it_wtxOrdered);
2229 [ # # # # ]: 0 : for (const auto& txin : it->second.GetTx()->vin) {
2230 : 0 : auto range = mapTxSpends.equal_range(txin.prevout);
2231 [ # # ]: 0 : for (auto iter = range.first; iter != range.second; ++iter) {
2232 [ # # ]: 0 : if (iter->second == hash) {
2233 : 0 : mapTxSpends.erase(iter);
2234 : 0 : break;
2235 : : }
2236 : : }
2237 : : }
2238 [ # # # # : 0 : for (unsigned int i = 0; i < it->second.GetTx()->vout.size(); ++i) {
# # ]
2239 : 0 : m_txos.erase(COutPoint(hash, i));
2240 : : }
2241 : 0 : mapWallet.erase(it);
2242 : 0 : NotifyTransactionChanged(hash, CT_DELETED);
2243 : : }
2244 : :
2245 : 0 : MarkDirty();
2246 : 0 : }, .on_abort={}});
2247 : :
2248 : 0 : return {};
2249 [ # # # # ]: 0 : }
2250 : :
2251 : 1972 : void CWallet::ClearInMemoryTxStateForTest()
2252 : : {
2253 : 1972 : AssertLockHeld(cs_wallet);
2254 : 1972 : mapWallet.clear();
2255 : 1972 : wtxOrdered.clear();
2256 : 1972 : mapTxSpends.clear();
2257 : 1972 : m_txos.clear();
2258 : 1972 : m_locked_coins.clear();
2259 : 1972 : nOrderPosNext = 0;
2260 : 1972 : }
2261 : :
2262 : 2640 : bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
2263 : : {
2264 : 2640 : bool fUpdated = false;
2265 : 2640 : bool is_mine;
2266 : 2640 : std::optional<AddressPurpose> purpose;
2267 : 2640 : {
2268 : 2640 : LOCK(cs_wallet);
2269 : 2640 : std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
2270 [ + + - + ]: 2640 : fUpdated = mi != m_address_book.end() && !mi->second.IsChange();
2271 : :
2272 [ + + + - ]: 2640 : CAddressBookData& record = mi != m_address_book.end() ? mi->second : m_address_book[address];
2273 [ - + ]: 5280 : record.SetLabel(strName);
2274 [ + - ]: 2640 : is_mine = IsMine(address);
2275 [ + - ]: 2640 : if (new_purpose) { /* update purpose only if requested */
2276 : 2640 : record.purpose = new_purpose;
2277 : : }
2278 [ + - ]: 2640 : purpose = record.purpose;
2279 : 0 : }
2280 : :
2281 : 2640 : const std::string& encoded_dest = EncodeDestination(address);
2282 [ + - + - : 5280 : if (new_purpose && !batch.WritePurpose(encoded_dest, PurposeToString(*new_purpose))) {
+ - - + -
+ ]
2283 [ # # ]: 0 : WalletLogPrintf("Error: fail to write address book 'purpose' entry");
2284 : : return false;
2285 : : }
2286 [ + - - + ]: 2640 : if (!batch.WriteName(encoded_dest, strName)) {
2287 [ # # ]: 0 : WalletLogPrintf("Error: fail to write address book 'name' entry");
2288 : : return false;
2289 : : }
2290 : :
2291 : : // In very old wallets, address purpose may not be recorded so we derive it from IsMine
2292 : 5280 : NotifyAddressBookChanged(address, strName, is_mine,
2293 [ + - + - ]: 5280 : purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND),
2294 [ + + - + ]: 5193 : (fUpdated ? CT_UPDATED : CT_NEW));
2295 : : return true;
2296 : 2640 : }
2297 : :
2298 : 2640 : bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose)
2299 : : {
2300 : 2640 : WalletBatch batch(GetDatabase());
2301 [ + - ]: 2640 : return SetAddressBookWithDB(batch, address, strName, purpose);
2302 : 2640 : }
2303 : :
2304 : 0 : bool CWallet::DelAddressBook(const CTxDestination& address)
2305 : : {
2306 [ # # ]: 0 : return RunWithinTxn(GetDatabase(), /*process_desc=*/"address book entry removal", [&](WalletBatch& batch){
2307 : 0 : return DelAddressBookWithDB(batch, address);
2308 : 0 : });
2309 : : }
2310 : :
2311 : 0 : bool CWallet::DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address)
2312 : : {
2313 : 0 : const std::string& dest = EncodeDestination(address);
2314 : 0 : {
2315 [ # # ]: 0 : LOCK(cs_wallet);
2316 : : // 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.
2317 : : // NOTE: This isn't a problem for sending addresses because they don't have any data that needs to be kept.
2318 : : // When adding new address data, it should be considered here whether to retain or delete it.
2319 [ # # # # ]: 0 : if (IsMine(address)) {
2320 [ # # ]: 0 : WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s", __func__, CLIENT_BUGREPORT);
2321 : : return false;
2322 : : }
2323 : : // Delete data rows associated with this address
2324 [ # # # # ]: 0 : if (!batch.EraseAddressData(address)) {
2325 [ # # ]: 0 : WalletLogPrintf("Error: cannot erase address book entry data");
2326 : : return false;
2327 : : }
2328 : :
2329 : : // Delete purpose entry
2330 [ # # # # ]: 0 : if (!batch.ErasePurpose(dest)) {
2331 [ # # ]: 0 : WalletLogPrintf("Error: cannot erase address book entry purpose");
2332 : : return false;
2333 : : }
2334 : :
2335 : : // Delete name entry
2336 [ # # # # ]: 0 : if (!batch.EraseName(dest)) {
2337 [ # # ]: 0 : WalletLogPrintf("Error: cannot erase address book entry name");
2338 : : return false;
2339 : : }
2340 : :
2341 : : // finally, remove it from the map
2342 [ # # ]: 0 : m_address_book.erase(address);
2343 : 0 : }
2344 : :
2345 : : // All good, signal changes
2346 [ # # ]: 0 : NotifyAddressBookChanged(address, "", /*is_mine=*/false, AddressPurpose::SEND, CT_DELETED);
2347 : : return true;
2348 : 0 : }
2349 : :
2350 : 0 : size_t CWallet::KeypoolCountExternalKeys() const
2351 : : {
2352 : 0 : AssertLockHeld(cs_wallet);
2353 : :
2354 : 0 : unsigned int count = 0;
2355 [ # # ]: 0 : for (auto spk_man : m_external_spk_managers) {
2356 : 0 : count += spk_man.second->GetKeyPoolSize();
2357 : : }
2358 : :
2359 : 0 : return count;
2360 : : }
2361 : :
2362 : 0 : unsigned int CWallet::GetKeyPoolSize() const
2363 : : {
2364 : 0 : AssertLockHeld(cs_wallet);
2365 : :
2366 : 0 : unsigned int count = 0;
2367 [ # # ]: 0 : for (auto spk_man : GetActiveScriptPubKeyMans()) {
2368 [ # # ]: 0 : count += spk_man->GetKeyPoolSize();
2369 : : }
2370 : 0 : return count;
2371 : : }
2372 : :
2373 : 0 : bool CWallet::TopUpKeyPool(unsigned int kpSize)
2374 : : {
2375 : 0 : LOCK(cs_wallet);
2376 : 0 : bool res = true;
2377 [ # # # # ]: 0 : for (auto spk_man : GetActiveScriptPubKeyMans()) {
2378 [ # # ]: 0 : res &= spk_man->TopUp(kpSize);
2379 : : }
2380 [ # # ]: 0 : return res;
2381 : 0 : }
2382 : :
2383 : 128 : util::Result<CTxDestination> CWallet::GetNewDestination(const OutputType type, const std::string& label)
2384 : : {
2385 : 128 : LOCK(cs_wallet);
2386 [ + - ]: 128 : auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
2387 [ - + ]: 128 : if (!spk_man) {
2388 [ # # # # ]: 0 : return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2389 : : }
2390 : :
2391 [ + - ]: 128 : auto op_dest = spk_man->GetNewDestination(type);
2392 [ + - ]: 128 : if (op_dest) {
2393 [ + - ]: 128 : SetAddressBook(*op_dest, label, AddressPurpose::RECEIVE);
2394 : : }
2395 : :
2396 : 128 : return op_dest;
2397 : 256 : }
2398 : :
2399 : 128 : util::Result<CTxDestination> CWallet::GetNewChangeDestination(const OutputType type)
2400 : : {
2401 : 128 : LOCK(cs_wallet);
2402 : :
2403 [ + - ]: 128 : ReserveDestination reservedest(this, type);
2404 [ + - ]: 128 : auto op_dest = reservedest.GetReservedDestination(true);
2405 [ + - + - ]: 128 : if (op_dest) reservedest.KeepDestination();
2406 : :
2407 : 128 : return op_dest;
2408 [ + - ]: 256 : }
2409 : :
2410 : 0 : void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
2411 [ # # # # ]: 0 : for (auto& entry : mapWallet) {
2412 : 0 : CWalletTx& wtx = entry.second;
2413 [ # # ]: 0 : if (wtx.m_is_cache_empty) continue;
2414 [ # # # # : 0 : for (unsigned int i = 0; i < wtx.GetTx()->vout.size(); i++) {
# # ]
2415 : 0 : CTxDestination dst;
2416 : 0 : if (ExtractDestination(wtx.GetTx()->vout[i].scriptPubKey, dst) && destinations.contains(dst)) {
[ # # # #
# # # # #
# # # ]
2417 : 0 : wtx.MarkDirty();
2418 : 0 : break;
2419 : : }
2420 : 0 : }
2421 : : }
2422 : 0 : }
2423 : :
2424 : 0 : void CWallet::ForEachAddrBookEntry(const ListAddrBookFunc& func) const
2425 : : {
2426 : 0 : AssertLockHeld(cs_wallet);
2427 [ # # ]: 0 : for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book) {
2428 : 0 : const auto& entry = item.second;
2429 [ # # ]: 0 : func(item.first, entry.GetLabel(), entry.IsChange(), entry.purpose);
2430 : : }
2431 : 0 : }
2432 : :
2433 : 0 : std::vector<CTxDestination> CWallet::ListAddrBookAddresses(const std::optional<AddrBookFilter>& _filter) const
2434 : : {
2435 : 0 : AssertLockHeld(cs_wallet);
2436 : 0 : std::vector<CTxDestination> result;
2437 [ # # # # ]: 0 : AddrBookFilter filter = _filter ? *_filter : AddrBookFilter();
2438 [ # # ]: 0 : ForEachAddrBookEntry([&result, &filter](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
2439 : : // Filter by change
2440 [ # # # # ]: 0 : if (filter.ignore_change && is_change) return;
2441 : : // Filter by label
2442 [ # # # # ]: 0 : if (filter.m_op_label && *filter.m_op_label != label) return;
2443 : : // All good
2444 : 0 : result.emplace_back(dest);
2445 : : });
2446 : 0 : return result;
2447 : 0 : }
2448 : :
2449 : 0 : std::set<std::string> CWallet::ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const
2450 : : {
2451 : 0 : AssertLockHeld(cs_wallet);
2452 [ # # ]: 0 : std::set<std::string> label_set;
2453 [ # # ]: 0 : ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label,
2454 : : bool _is_change, const std::optional<AddressPurpose>& _purpose) {
2455 [ # # ]: 0 : if (_is_change) return;
2456 [ # # # # ]: 0 : if (!purpose || purpose == _purpose) {
2457 : 0 : label_set.insert(_label);
2458 : : }
2459 : : });
2460 : 0 : return label_set;
2461 : 0 : }
2462 : :
2463 : 625 : util::Result<CTxDestination> ReserveDestination::GetReservedDestination(bool internal)
2464 : : {
2465 : 625 : m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
2466 [ - + ]: 625 : if (!m_spk_man) {
2467 : 0 : return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2468 : : }
2469 : :
2470 [ + - ]: 625 : if (nIndex == -1) {
2471 : 625 : int64_t index;
2472 : 625 : auto op_address = m_spk_man->GetReservedDestination(type, internal, index);
2473 [ - + ]: 625 : if (!op_address) return op_address;
2474 : 625 : nIndex = index;
2475 [ + - ]: 1250 : address = *op_address;
2476 : 625 : }
2477 : 625 : return address;
2478 : : }
2479 : :
2480 : 1187 : void ReserveDestination::KeepDestination()
2481 : : {
2482 [ + + ]: 1187 : if (nIndex != -1) {
2483 : 308 : m_spk_man->KeepDestination(nIndex, type);
2484 : : }
2485 : 1187 : nIndex = -1;
2486 : 1187 : address = CNoDestination();
2487 : 1187 : }
2488 : :
2489 : 2282 : void ReserveDestination::ReturnDestination()
2490 : : {
2491 [ + + ]: 2282 : if (nIndex != -1) {
2492 : 317 : m_spk_man->ReturnDestination(nIndex, fInternal, address);
2493 : : }
2494 : 2282 : nIndex = -1;
2495 : 2282 : address = CNoDestination();
2496 : 2282 : }
2497 : :
2498 : 0 : util::Result<void> CWallet::DisplayAddress(const CTxDestination& dest)
2499 : : {
2500 : 0 : CScript scriptPubKey = GetScriptForDestination(dest);
2501 [ # # # # ]: 0 : for (const auto& spk_man : GetScriptPubKeyMans(scriptPubKey)) {
2502 [ # # ]: 0 : auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan *>(spk_man);
2503 [ # # ]: 0 : if (signer_spk_man == nullptr) {
2504 : 0 : continue;
2505 : : }
2506 [ # # ]: 0 : auto signer{ExternalSignerScriptPubKeyMan::GetExternalSigner()};
2507 [ # # # # : 0 : if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
# # ]
2508 [ # # ]: 0 : return signer_spk_man->DisplayAddress(dest, *signer);
2509 : 0 : }
2510 [ # # ]: 0 : return util::Error{_("There is no ScriptPubKeyManager for this address")};
2511 : 0 : }
2512 : :
2513 : 0 : void CWallet::LoadLockedCoin(const COutPoint& coin, bool persistent)
2514 : : {
2515 : 0 : AssertLockHeld(cs_wallet);
2516 : 0 : m_locked_coins.emplace(coin, persistent);
2517 : 0 : }
2518 : :
2519 : 0 : bool CWallet::LockCoin(const COutPoint& output, bool persist)
2520 : : {
2521 : 0 : AssertLockHeld(cs_wallet);
2522 : 0 : LoadLockedCoin(output, persist);
2523 [ # # ]: 0 : if (persist) {
2524 : 0 : WalletBatch batch(GetDatabase());
2525 [ # # ]: 0 : return batch.WriteLockedUTXO(output);
2526 : 0 : }
2527 : : return true;
2528 : : }
2529 : :
2530 : 0 : bool CWallet::UnlockCoin(const COutPoint& output)
2531 : : {
2532 : 0 : AssertLockHeld(cs_wallet);
2533 : 0 : auto locked_coin_it = m_locked_coins.find(output);
2534 [ # # ]: 0 : if (locked_coin_it != m_locked_coins.end()) {
2535 : 0 : bool persisted = locked_coin_it->second;
2536 : 0 : m_locked_coins.erase(locked_coin_it);
2537 [ # # ]: 0 : if (persisted) {
2538 : 0 : WalletBatch batch(GetDatabase());
2539 [ # # ]: 0 : return batch.EraseLockedUTXO(output);
2540 : 0 : }
2541 : : }
2542 : : return true;
2543 : : }
2544 : :
2545 : 0 : bool CWallet::UnlockAllCoins()
2546 : : {
2547 : 0 : AssertLockHeld(cs_wallet);
2548 : 0 : bool success = true;
2549 : 0 : WalletBatch batch(GetDatabase());
2550 [ # # # # ]: 0 : for (const auto& [coin, persistent] : m_locked_coins) {
2551 [ # # # # : 0 : if (persistent) success = success && batch.EraseLockedUTXO(coin);
# # # # ]
2552 : : }
2553 : 0 : m_locked_coins.clear();
2554 : 0 : return success;
2555 : 0 : }
2556 : :
2557 : 284055 : bool CWallet::IsLockedCoin(const COutPoint& output) const
2558 : : {
2559 : 284055 : AssertLockHeld(cs_wallet);
2560 : 284055 : return m_locked_coins.contains(output);
2561 : : }
2562 : :
2563 : 0 : void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
2564 : : {
2565 : 0 : AssertLockHeld(cs_wallet);
2566 [ # # ]: 0 : for (const auto& [coin, _] : m_locked_coins) {
2567 : 0 : vOutpts.push_back(coin);
2568 : : }
2569 : 0 : }
2570 : :
2571 : : /**
2572 : : * Compute smart timestamp for a transaction being added to the wallet.
2573 : : *
2574 : : * Logic:
2575 : : * - If sending a transaction, assign its timestamp to the current time.
2576 : : * - If receiving a transaction outside a block, assign its timestamp to the
2577 : : * current time.
2578 : : * - If receiving a transaction during a rescanning process, assign all its
2579 : : * (not already known) transactions' timestamps to the block time.
2580 : : * - If receiving a block with a future timestamp, assign all its (not already
2581 : : * known) transactions' timestamps to the current time.
2582 : : * - If receiving a block with a past timestamp, before the most recent known
2583 : : * transaction (that we care about), assign all its (not already known)
2584 : : * transactions' timestamps to the same timestamp as that most-recent-known
2585 : : * transaction.
2586 : : * - If receiving a block with a past timestamp, but after the most recent known
2587 : : * transaction, assign all its (not already known) transactions' timestamps to
2588 : : * the block time.
2589 : : *
2590 : : * For more information see CWalletTx::nTimeSmart,
2591 : : * https://bitcointalk.org/?topic=54527, or
2592 : : * https://github.com/bitcoin/bitcoin/pull/1393.
2593 : : */
2594 : 0 : unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
2595 : : {
2596 : 0 : std::optional<uint256> block_hash;
2597 [ # # ]: 0 : if (auto* conf = wtx.state<TxStateConfirmed>()) {
2598 : 0 : block_hash = conf->confirmed_block_hash;
2599 [ # # ]: 0 : } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
2600 : 0 : block_hash = conf->conflicting_block_hash;
2601 : : }
2602 : :
2603 : 0 : unsigned int nTimeSmart = wtx.nTimeReceived;
2604 [ # # ]: 0 : if (block_hash) {
2605 : 0 : int64_t blocktime;
2606 : 0 : int64_t block_max_time;
2607 [ # # ]: 0 : if (chain().findBlock(*block_hash, FoundBlock().time(blocktime).maxTime(block_max_time))) {
2608 [ # # ]: 0 : if (rescanning_old_block) {
2609 : 0 : nTimeSmart = block_max_time;
2610 : : } else {
2611 : 0 : int64_t latestNow = wtx.nTimeReceived;
2612 : 0 : int64_t latestEntry = 0;
2613 : :
2614 : : // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
2615 : 0 : int64_t latestTolerated = latestNow + 300;
2616 : 0 : const TxItems& txOrdered = wtxOrdered;
2617 [ # # ]: 0 : for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2618 : 0 : CWalletTx* const pwtx = it->second;
2619 [ # # ]: 0 : if (pwtx == &wtx) {
2620 : 0 : continue;
2621 : : }
2622 : 0 : int64_t nSmartTime;
2623 : 0 : nSmartTime = pwtx->nTimeSmart;
2624 [ # # ]: 0 : if (!nSmartTime) {
2625 : 0 : nSmartTime = pwtx->nTimeReceived;
2626 : : }
2627 [ # # ]: 0 : if (nSmartTime <= latestTolerated) {
2628 : 0 : latestEntry = nSmartTime;
2629 [ # # ]: 0 : if (nSmartTime > latestNow) {
2630 : 0 : latestNow = nSmartTime;
2631 : : }
2632 : : break;
2633 : : }
2634 : : }
2635 : :
2636 [ # # # # ]: 0 : nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2637 : : }
2638 : : } else {
2639 [ # # # # : 0 : WalletLogPrintf("%s: found %s in block %s not in index", __func__, wtx.GetHash().ToString(), block_hash->ToString());
# # ]
2640 : : }
2641 : : }
2642 : 0 : return nTimeSmart;
2643 : : }
2644 : :
2645 : 0 : bool CWallet::SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used)
2646 : : {
2647 [ # # ]: 0 : if (std::get_if<CNoDestination>(&dest))
2648 : : return false;
2649 : :
2650 [ # # ]: 0 : if (!used) {
2651 [ # # ]: 0 : if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false;
2652 : 0 : return batch.WriteAddressPreviouslySpent(dest, false);
2653 : : }
2654 : :
2655 : 0 : LoadAddressPreviouslySpent(dest);
2656 : 0 : return batch.WriteAddressPreviouslySpent(dest, true);
2657 : : }
2658 : :
2659 : 0 : void CWallet::LoadAddressPreviouslySpent(const CTxDestination& dest)
2660 : : {
2661 : 0 : m_address_book[dest].previously_spent = true;
2662 : 0 : }
2663 : :
2664 : 0 : void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request)
2665 : : {
2666 : 0 : m_address_book[dest].receive_requests[id] = request;
2667 : 0 : }
2668 : :
2669 : 0 : bool CWallet::IsAddressPreviouslySpent(const CTxDestination& dest) const
2670 : : {
2671 [ # # ]: 0 : if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent;
2672 : : return false;
2673 : : }
2674 : :
2675 : 0 : std::vector<std::string> CWallet::GetAddressReceiveRequests() const
2676 : : {
2677 : 0 : std::vector<std::string> values;
2678 [ # # ]: 0 : for (const auto& [dest, entry] : m_address_book) {
2679 [ # # # # ]: 0 : for (const auto& [id, request] : entry.receive_requests) {
2680 [ # # ]: 0 : values.emplace_back(request);
2681 : : }
2682 : : }
2683 : 0 : return values;
2684 : 0 : }
2685 : :
2686 : 0 : bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
2687 : : {
2688 [ # # ]: 0 : if (!batch.WriteAddressReceiveRequest(dest, id, value)) return false;
2689 : 0 : m_address_book[dest].receive_requests[id] = value;
2690 : 0 : return true;
2691 : : }
2692 : :
2693 : 0 : bool CWallet::EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id)
2694 : : {
2695 [ # # ]: 0 : if (!batch.EraseAddressReceiveRequest(dest, id)) return false;
2696 : 0 : m_address_book[dest].receive_requests.erase(id);
2697 : 0 : return true;
2698 : : }
2699 : :
2700 : 0 : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
2701 : : {
2702 : 0 : const auto& wallet_path = GetWalletPath(name);
2703 [ # # ]: 0 : if (!wallet_path) {
2704 [ # # ]: 0 : error_string = util::ErrorString(wallet_path);
2705 : 0 : status = DatabaseStatus::FAILED_BAD_PATH;
2706 : 0 : return nullptr;
2707 : : }
2708 [ # # ]: 0 : return MakeDatabase(*wallet_path, options, status, error_string);
2709 : 0 : }
2710 : :
2711 : 0 : bool CWallet::LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings)
2712 : : {
2713 : 0 : interfaces::Chain* chain = context.chain;
2714 : 0 : const ArgsManager& args = *Assert(context.args);
2715 : :
2716 [ # # # # : 0 : if (!args.GetArg("-addresstype", "").empty()) {
# # ]
2717 [ # # # # : 0 : std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-addresstype", ""));
# # ]
2718 [ # # ]: 0 : if (!parsed) {
2719 [ # # # # : 0 : error = strprintf(_("Unknown address type '%s'"), args.GetArg("-addresstype", ""));
# # ]
2720 : 0 : return false;
2721 : : }
2722 : 0 : wallet->m_default_address_type = parsed.value();
2723 : : }
2724 : :
2725 [ # # # # : 0 : if (!args.GetArg("-changetype", "").empty()) {
# # ]
2726 [ # # # # : 0 : std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-changetype", ""));
# # ]
2727 [ # # ]: 0 : if (!parsed) {
2728 [ # # # # : 0 : error = strprintf(_("Unknown change type '%s'"), args.GetArg("-changetype", ""));
# # ]
2729 : 0 : return false;
2730 : : }
2731 : 0 : wallet->m_default_change_type = parsed.value();
2732 : : }
2733 : :
2734 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-mintxfee")}) {
2735 [ # # ]: 0 : std::optional<CAmount> min_tx_fee = ParseMoney(*arg);
2736 [ # # ]: 0 : if (!min_tx_fee) {
2737 [ # # # # ]: 0 : error = AmountErrMsg("mintxfee", *arg);
2738 : 0 : return false;
2739 [ # # ]: 0 : } else if (min_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
2740 [ # # # # : 0 : warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
# # ]
2741 [ # # # # ]: 0 : _("This is the minimum transaction fee you pay on every transaction."));
2742 : : }
2743 : :
2744 : 0 : wallet->m_min_fee = CFeeRate{min_tx_fee.value()};
2745 : 0 : }
2746 : :
2747 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-maxapsfee")}) {
2748 [ # # ]: 0 : const std::string& max_aps_fee_str{*arg};
2749 [ # # ]: 0 : if (max_aps_fee_str == "-1") {
2750 : 0 : wallet->m_max_aps_fee = -1;
2751 [ # # # # ]: 0 : } else if (std::optional<CAmount> max_aps_fee = ParseMoney(max_aps_fee_str)) {
2752 [ # # ]: 0 : if (max_aps_fee.value() > HIGH_APS_FEE) {
2753 [ # # # # : 0 : warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
# # ]
2754 [ # # # # ]: 0 : _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
2755 : : }
2756 : 0 : wallet->m_max_aps_fee = max_aps_fee.value();
2757 : : } else {
2758 [ # # # # ]: 0 : error = AmountErrMsg("maxapsfee", max_aps_fee_str);
2759 : 0 : return false;
2760 : : }
2761 : 0 : }
2762 : :
2763 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-fallbackfee")}) {
2764 [ # # ]: 0 : std::optional<CAmount> fallback_fee = ParseMoney(*arg);
2765 [ # # ]: 0 : if (!fallback_fee) {
2766 [ # # ]: 0 : error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-fallbackfee", *arg);
2767 : 0 : return false;
2768 [ # # ]: 0 : } else if (fallback_fee.value() > HIGH_TX_FEE_PER_KB) {
2769 [ # # # # : 0 : warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
# # ]
2770 [ # # # # ]: 0 : _("This is the transaction fee you may pay when fee estimates are not available."));
2771 : : }
2772 : 0 : wallet->m_fallback_fee = CFeeRate{fallback_fee.value()};
2773 : 0 : }
2774 : :
2775 : : // Disable fallback fee in case value was set to 0, enable if non-null value
2776 : 0 : wallet->m_allow_fallback_fee = wallet->m_fallback_fee.GetFeePerK() != 0;
2777 : :
2778 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-discardfee")}) {
2779 [ # # ]: 0 : std::optional<CAmount> discard_fee = ParseMoney(*arg);
2780 [ # # ]: 0 : if (!discard_fee) {
2781 [ # # ]: 0 : error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-discardfee", *arg);
2782 : 0 : return false;
2783 [ # # ]: 0 : } else if (discard_fee.value() > HIGH_TX_FEE_PER_KB) {
2784 [ # # # # : 0 : warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
# # ]
2785 [ # # # # ]: 0 : _("This is the transaction fee you may discard if change is smaller than dust at this level"));
2786 : : }
2787 : 0 : wallet->m_discard_rate = CFeeRate{discard_fee.value()};
2788 : 0 : }
2789 : :
2790 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-maxtxfee")}) {
2791 [ # # ]: 0 : std::optional<CAmount> max_tx_fee = ParseMoney(*arg);
2792 [ # # ]: 0 : if (!max_tx_fee) {
2793 [ # # # # ]: 0 : error = AmountErrMsg("maxtxfee", *arg);
2794 : 0 : return false;
2795 [ # # ]: 0 : } else if (max_tx_fee.value() > HIGH_MAX_TX_FEE) {
2796 [ # # ]: 0 : warnings.push_back(strprintf(_("%s is set very high! Fees this large could be paid on a single transaction."), "-maxtxfee"));
2797 : : }
2798 [ # # # # ]: 0 : const CFeeRate max_txfee{max_tx_fee.value(), 1000};
2799 [ # # # # : 0 : if (chain && max_txfee < chain->relayMinFee()) {
# # ]
2800 : : // Wallet prevents creating transactions with fee rates lower than minrelaytxfee.
2801 : : // Also the wallet prevents creating transactions with base fee above maxtxfee.
2802 : : // Warn when a 1kvb transaction, with a base fee set to maxtxfee, has a fee rate less than minrelaytxfee.
2803 : : // It is likely that some transactions with fee rates greater than or equal to the minrelaytxfee will exceed maxtxfee.
2804 : : // In such cases, the wallet won't be able to create transactions. Therefore, warn the user.
2805 [ # # ]: 0 : warnings.push_back(strprintf(_("Invalid amount for %s=<amount>: '%s' conflicts with the minimum relay transaction feerate %s. Please set a higher %s or lower %s"),
2806 [ # # # # : 0 : "-maxtxfee", max_txfee.ToString(), chain->relayMinFee().ToString(), "-maxtxfee", "-minrelaytxfee"));
# # ]
2807 : : }
2808 : :
2809 [ # # ]: 0 : wallet->m_max_tx_fee = max_tx_fee.value();
2810 : 0 : }
2811 : :
2812 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-maxfeerate")}) {
2813 [ # # ]: 0 : std::optional<CAmount> max_tx_fee_rate = ParseMoney(*arg);
2814 [ # # ]: 0 : if (!max_tx_fee_rate) {
2815 [ # # # # ]: 0 : error = AmountErrMsg("maxfeerate", *arg);
2816 : 0 : return false;
2817 : : }
2818 [ # # # # : 0 : if (chain && CFeeRate(*max_tx_fee_rate) < chain->relayMinFee()) {
# # ]
2819 [ # # ]: 0 : error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
2820 [ # # # # ]: 0 : "-maxfeerate", *arg, chain->relayMinFee().ToString());
2821 : 0 : return false;
2822 : : }
2823 [ # # ]: 0 : if (CFeeRate(*max_tx_fee_rate) > HIGH_MAX_TX_FEERATE) {
2824 [ # # ]: 0 : warnings.push_back(strprintf(_("%s is set very high! Fee rate this large could be paid on a single transaction."), "-maxfeerate"));
2825 : : }
2826 : :
2827 : 0 : wallet->m_max_tx_fee_rate = CFeeRate(*max_tx_fee_rate);
2828 : 0 : }
2829 : :
2830 [ # # # # ]: 0 : if (const auto arg{args.GetArg("-consolidatefeerate")}) {
2831 [ # # # # ]: 0 : if (std::optional<CAmount> consolidate_feerate = ParseMoney(*arg)) {
2832 : 0 : wallet->m_consolidate_feerate = CFeeRate(*consolidate_feerate);
2833 : : } else {
2834 [ # # # # ]: 0 : error = AmountErrMsg("consolidatefeerate", *arg);
2835 : 0 : return false;
2836 : : }
2837 : 0 : }
2838 : :
2839 [ # # # # ]: 0 : if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
2840 [ # # # # : 0 : warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
# # ]
2841 [ # # ]: 0 : _("The wallet will avoid paying less than the minimum relay fee."));
2842 : : }
2843 : :
2844 : 0 : wallet->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
2845 [ # # ]: 0 : wallet->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
2846 : 0 : wallet->m_signal_rbf = DEFAULT_WALLET_RBF;
2847 [ # # # # ]: 0 : if (auto value{args.GetBoolArg("-walletrbf")}) {
2848 [ # # ]: 0 : warnings.push_back(_("-walletrbf is deprecated and will be fully removed in the next release."));
2849 : 0 : wallet->m_signal_rbf = *value;
2850 : : }
2851 : :
2852 [ # # ]: 0 : wallet->m_keypool_size = std::max(args.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{1});
2853 [ # # # # ]: 0 : wallet->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
2854 [ # # ]: 0 : wallet->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
2855 : :
2856 : 0 : return true;
2857 : : }
2858 : :
2859 : 0 : std::shared_ptr<CWallet> CWallet::CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bool born_encrypted, bilingual_str& error, std::vector<bilingual_str>& warnings)
2860 : : {
2861 : 0 : interfaces::Chain* chain = context.chain;
2862 : 0 : const std::string& walletFile = database->Filename();
2863 : :
2864 : 0 : const auto start{SteadyClock::now()};
2865 : : // TODO: Can't use std::make_shared because we need a custom deleter but
2866 : : // should be possible to use std::allocate_shared.
2867 [ # # # # : 0 : std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
# # # # ]
2868 : :
2869 [ # # # # : 0 : if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
# # # # ]
2870 : 0 : return nullptr;
2871 : : }
2872 : :
2873 : : // Initialize version key.
2874 : 0 : {
2875 [ # # ]: 0 : WalletBatch batch(walletInstance->GetDatabase());
2876 [ # # # # ]: 0 : if(!batch.WriteLastOpenedVersion()) {
2877 [ # # ]: 0 : error = strprintf(_("Error creating %s: Could not write version metadata."), walletFile);
2878 : 0 : return nullptr;
2879 : : }
2880 [ # # # # ]: 0 : if(!batch.WriteLastOpenedFeatures()) {
2881 [ # # ]: 0 : error = strprintf(_("Error creating %s: Could not write features metadata."), walletFile);
2882 : 0 : return nullptr;
2883 : : }
2884 : 0 : }
2885 : 0 : {
2886 [ # # ]: 0 : LOCK(walletInstance->cs_wallet);
2887 : :
2888 : : // Init with passed flags.
2889 : : // Always set the cache upgrade flag as this feature is supported from the beginning.
2890 [ # # ]: 0 : walletInstance->InitWalletFlags(wallet_creation_flags | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
2891 : :
2892 : : // Only descriptor wallets can be created
2893 [ # # # # ]: 0 : assert(walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
2894 : :
2895 : : // Born encrypted wallets will have their keys generated later
2896 [ # # ]: 0 : if (!born_encrypted) {
2897 [ # # ]: 0 : walletInstance->SetupWalletGeneration();
2898 : : }
2899 : :
2900 [ # # ]: 0 : if (chain) {
2901 [ # # ]: 0 : std::optional<int> tip_height = chain->getHeight();
2902 [ # # ]: 0 : if (tip_height) {
2903 [ # # # # ]: 0 : walletInstance->SetLastBlockProcessed(*tip_height, chain->getBlockHash(*tip_height));
2904 : : }
2905 : : }
2906 : 0 : }
2907 : :
2908 [ # # ]: 0 : walletInstance->WalletLogPrintf("Wallet completed creation in %15dms", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
2909 : :
2910 : : // Try to top up keypool. No-op if the wallet is locked.
2911 [ # # ]: 0 : walletInstance->TopUpKeyPool();
2912 : :
2913 [ # # # # : 0 : if (chain && !AttachChain(walletInstance, *chain, /*rescan_required=*/false, error, warnings)) {
# # ]
2914 [ # # ]: 0 : walletInstance->DisconnectChainNotifications();
2915 : 0 : return nullptr;
2916 : : }
2917 : :
2918 : 0 : return walletInstance;
2919 : 0 : }
2920 : :
2921 : 0 : std::shared_ptr<CWallet> CWallet::LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings)
2922 : : {
2923 : 0 : interfaces::Chain* chain = context.chain;
2924 : 0 : const std::string& walletFile = database->Filename();
2925 : :
2926 : 0 : const auto start{SteadyClock::now()};
2927 [ # # # # : 0 : std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
# # # # ]
2928 : :
2929 [ # # # # : 0 : if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
# # # # ]
2930 : 0 : return nullptr;
2931 : : }
2932 : :
2933 : : // Load wallet
2934 [ # # ]: 0 : auto nLoadWalletRet = walletInstance->PopulateWalletFromDB(error, warnings);
2935 : 0 : bool rescan_required = nLoadWalletRet == DBErrors::NEED_RESCAN;
2936 [ # # # # ]: 0 : if (nLoadWalletRet != DBErrors::LOAD_OK && nLoadWalletRet != DBErrors::NONCRITICAL_ERROR && !rescan_required) {
2937 : 0 : return nullptr;
2938 : : }
2939 : :
2940 [ # # # # ]: 0 : if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
2941 [ # # # # ]: 0 : for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2942 [ # # # # ]: 0 : if (spk_man->HavePrivateKeys()) {
2943 [ # # ]: 0 : warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
2944 : 0 : break;
2945 : : }
2946 : : }
2947 : : }
2948 : :
2949 [ # # ]: 0 : walletInstance->WalletLogPrintf("Wallet completed loading in %15dms", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
2950 : :
2951 : : // Try to top up keypool. No-op if the wallet is locked.
2952 [ # # ]: 0 : walletInstance->TopUpKeyPool();
2953 : :
2954 [ # # # # : 0 : if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
# # ]
2955 [ # # ]: 0 : walletInstance->DisconnectChainNotifications();
2956 : 0 : return nullptr;
2957 : : }
2958 : :
2959 [ # # # # ]: 0 : WITH_LOCK(walletInstance->cs_wallet, walletInstance->LogStats());
2960 : :
2961 : 0 : return walletInstance;
2962 : 0 : }
2963 : :
2964 : :
2965 : 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)
2966 : : {
2967 : 0 : LOCK(walletInstance->cs_wallet);
2968 : : // allow setting the chain if it hasn't been set already but prevent changing it
2969 [ # # # # ]: 0 : assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
2970 [ # # ]: 0 : walletInstance->m_chain = &chain;
2971 : :
2972 : : // Unless allowed, ensure wallet files are not reused across chains:
2973 [ # # # # : 0 : if (!gArgs.GetBoolArg("-walletcrosschain", DEFAULT_WALLETCROSSCHAIN)) {
# # ]
2974 [ # # ]: 0 : WalletBatch batch(walletInstance->GetDatabase());
2975 : 0 : CBlockLocator locator;
2976 [ # # # # : 0 : if (batch.ReadBestBlock(locator) && locator.vHave.size() > 0 && chain.getHeight()) {
# # # # #
# ]
2977 : : // Wallet is assumed to be from another chain, if genesis block in the active
2978 : : // chain differs from the genesis block known to the wallet.
2979 [ # # ]: 0 : if (chain.getBlockHash(0) != locator.vHave.back()) {
2980 [ # # # # ]: 0 : error = Untranslated("Wallet files should not be reused across chains. Restart bitcoind with -walletcrosschain to override.");
2981 : 0 : return false;
2982 : : }
2983 : : }
2984 : 0 : }
2985 : :
2986 : : // Register wallet with validationinterface. It's done before rescan to avoid
2987 : : // missing block connections during the rescan.
2988 : : // Because of the wallet lock being held, block connection notifications are going to
2989 : : // be pending on the validation-side until lock release. Blocks that are connected while the
2990 : : // rescan is ongoing will not be processed in the rescan but with the block connected notifications,
2991 : : // so the wallet will only be completeley synced after the notifications delivery.
2992 [ # # # # ]: 0 : walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
2993 : :
2994 : : // If rescan_required = true, rescan_height remains equal to 0
2995 : 0 : int rescan_height = 0;
2996 [ # # ]: 0 : if (!rescan_required)
2997 : : {
2998 [ # # ]: 0 : WalletBatch batch(walletInstance->GetDatabase());
2999 : 0 : CBlockLocator locator;
3000 [ # # # # ]: 0 : if (batch.ReadBestBlock(locator)) {
3001 [ # # # # ]: 0 : if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
3002 : 0 : rescan_height = *fork_height;
3003 : : }
3004 : : }
3005 : 0 : }
3006 : :
3007 [ # # ]: 0 : const std::optional<int> tip_height = chain.getHeight();
3008 [ # # ]: 0 : if (tip_height) {
3009 [ # # # # ]: 0 : walletInstance->SetLastBlockProcessedInMem(*tip_height, chain.getBlockHash(*tip_height));
3010 : : } else {
3011 [ # # ]: 0 : walletInstance->SetLastBlockProcessedInMem(-1, uint256());
3012 : : }
3013 : :
3014 [ # # # # ]: 0 : if (tip_height && *tip_height != rescan_height)
3015 : : {
3016 : : // No need to read and scan block if block was created before
3017 : : // our wallet birthday (as adjusted for block time variability)
3018 [ # # ]: 0 : std::optional<int64_t> time_first_key = walletInstance->m_birth_time.load();
3019 [ # # ]: 0 : if (time_first_key) {
3020 [ # # ]: 0 : FoundBlock found = FoundBlock().height(rescan_height);
3021 [ # # ]: 0 : chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
3022 [ # # ]: 0 : if (!found.found) {
3023 : : // We were unable to find a block that had a time more recent than our earliest timestamp
3024 : : // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
3025 : : // current chain tip. Skip rescanning in this case.
3026 : 0 : rescan_height = *tip_height;
3027 : : }
3028 : : }
3029 : :
3030 : : // Technically we could execute the code below in any case, but performing the
3031 : : // `while` loop below can make startup very slow, so only check blocks on disk
3032 : : // if necessary.
3033 [ # # # # : 0 : if (chain.havePruned() || chain.hasAssumedValidChain()) {
# # # # ]
3034 : 0 : int block_height = *tip_height;
3035 [ # # # # : 0 : while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
# # # # ]
3036 : 0 : --block_height;
3037 : : }
3038 : :
3039 [ # # ]: 0 : if (rescan_height != block_height) {
3040 : : // We can't rescan beyond blocks we don't have data for, stop and throw an error.
3041 : : // This might happen if a user uses an old wallet within a pruned node
3042 : : // or if they ran -disablewallet for a longer time, then decided to re-enable
3043 : : // Exit early and print an error.
3044 : : // It also may happen if an assumed-valid chain is in use and therefore not
3045 : : // all block data is available.
3046 : : // If a block is pruned after this check, we will load the wallet,
3047 : : // but fail the rescan with a generic error.
3048 : :
3049 [ # # # # : 0 : error = chain.havePruned() ?
# # ]
3050 [ # # ]: 0 : _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of a pruned node)") :
3051 : : strprintf(_(
3052 : : "Error loading wallet. Wallet requires blocks to be downloaded, "
3053 : : "and software does not currently support loading wallets while "
3054 : : "blocks are being downloaded out of order when using assumeutxo "
3055 : : "snapshots. Wallet should be able to load successfully after "
3056 : 0 : "node sync reaches height %s"), block_height);
3057 : 0 : return false;
3058 : : }
3059 : : }
3060 : :
3061 [ # # # # ]: 0 : chain.initMessage(_("Rescanning…"));
3062 [ # # ]: 0 : walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...", *tip_height - rescan_height, rescan_height);
3063 : :
3064 : 0 : {
3065 [ # # ]: 0 : WalletRescanReserver reserver(*walletInstance);
3066 [ # # # # ]: 0 : if (!reserver.reserve()) {
3067 [ # # ]: 0 : error = _("Failed to acquire rescan reserver during wallet initialization");
3068 : 0 : return false;
3069 : : }
3070 [ # # # # : 0 : ScanResult scan_res = walletInstance->Scanner().Scan(chain.getBlockHash(rescan_height), rescan_height, /*max_height=*/{}, reserver, /*save_progress=*/true);
# # ]
3071 [ # # ]: 0 : if (ScanResult::SUCCESS != scan_res.status) {
3072 [ # # ]: 0 : error = _("Failed to rescan the wallet during initialization");
3073 : 0 : return false;
3074 : : }
3075 : : // Set and update the best block record
3076 : : // Set last block scanned as the last block processed as it may be different in case of a reorg.
3077 : : // Also save the best block locator because rescanning only updates it intermittently.
3078 [ # # ]: 0 : walletInstance->SetLastBlockProcessed(*scan_res.last_scanned_height, scan_res.last_scanned_block);
3079 : 0 : }
3080 : : }
3081 : :
3082 : : return true;
3083 : 0 : }
3084 : :
3085 : 0 : const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
3086 : : {
3087 : 0 : const auto& address_book_it = m_address_book.find(dest);
3088 [ # # ]: 0 : if (address_book_it == m_address_book.end()) return nullptr;
3089 [ # # # # ]: 0 : if ((!allow_change) && address_book_it->second.IsChange()) {
3090 : : return nullptr;
3091 : : }
3092 : 0 : return &address_book_it->second;
3093 : : }
3094 : :
3095 : 0 : void CWallet::postInitProcess()
3096 : : {
3097 : : // Add wallet transactions that aren't already in a block to mempool
3098 : : // Do this here as mempool requires genesis block to be loaded
3099 : 0 : ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_NO_BROADCAST, /*force=*/true);
3100 : :
3101 : : // Update wallet transactions with current mempool transactions.
3102 [ # # ]: 0 : WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
3103 : 0 : }
3104 : :
3105 : 0 : bool CWallet::BackupWallet(const std::string& strDest) const
3106 : : {
3107 [ # # ]: 0 : WITH_LOCK(cs_wallet, WriteBestBlock());
3108 : 0 : return GetDatabase().Backup(strDest);
3109 : : }
3110 : :
3111 : 329308 : int CWallet::GetTxDepthInMainChain(const CWalletTx& wtx) const
3112 : : {
3113 : 329308 : AssertLockHeld(cs_wallet);
3114 [ - + ]: 329308 : if (auto* conf = wtx.state<TxStateConfirmed>()) {
3115 [ - + ]: 329308 : assert(conf->confirmed_block_height >= 0);
3116 : 329308 : return GetLastBlockHeight() - conf->confirmed_block_height + 1;
3117 [ # # ]: 0 : } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
3118 [ # # ]: 0 : assert(conf->conflicting_block_height >= 0);
3119 : 0 : return -1 * (GetLastBlockHeight() - conf->conflicting_block_height + 1);
3120 : : } else {
3121 : : return 0;
3122 : : }
3123 : : }
3124 : :
3125 : 329308 : int CWallet::GetTxBlocksToMaturity(const CWalletTx& wtx) const
3126 : : {
3127 : 329308 : AssertLockHeld(cs_wallet);
3128 : :
3129 [ - + ]: 329308 : if (!wtx.IsCoinBase()) {
3130 : : return 0;
3131 : : }
3132 : 0 : int chain_depth = GetTxDepthInMainChain(wtx);
3133 [ # # ]: 0 : assert(chain_depth >= 0); // coinbase tx should not be conflicted
3134 [ # # ]: 0 : return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
3135 : : }
3136 : :
3137 : 329308 : bool CWallet::IsTxImmatureCoinBase(const CWalletTx& wtx) const
3138 : : {
3139 : 329308 : AssertLockHeld(cs_wallet);
3140 : :
3141 : : // note GetTxBlocksToMaturity is 0 for non-coinbase tx
3142 : 329308 : return GetTxBlocksToMaturity(wtx) > 0;
3143 : : }
3144 : :
3145 : 1591 : bool CWallet::IsLocked() const
3146 : : {
3147 [ - + ]: 1591 : if (!HasEncryptionKeys()) {
3148 : : return false;
3149 : : }
3150 : 0 : LOCK(cs_wallet);
3151 [ # # ]: 0 : return vMasterKey.empty();
3152 : 0 : }
3153 : :
3154 : 0 : bool CWallet::Lock()
3155 : : {
3156 [ # # ]: 0 : if (!HasEncryptionKeys())
3157 : : return false;
3158 : :
3159 : 0 : {
3160 [ # # ]: 0 : LOCK2(m_relock_mutex, cs_wallet);
3161 [ # # ]: 0 : if (!vMasterKey.empty()) {
3162 [ # # # # ]: 0 : memory_cleanse(vMasterKey.data(), vMasterKey.size() * sizeof(decltype(vMasterKey)::value_type));
3163 [ # # # # ]: 0 : vMasterKey.clear();
3164 : : }
3165 [ # # ]: 0 : }
3166 : :
3167 : 0 : NotifyStatusChanged(this);
3168 : 0 : return true;
3169 : : }
3170 : :
3171 : 0 : bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
3172 : : {
3173 : 0 : {
3174 : 0 : LOCK(cs_wallet);
3175 [ # # ]: 0 : for (const auto& spk_man_pair : m_spk_managers) {
3176 [ # # # # ]: 0 : if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn)) {
3177 [ # # ]: 0 : return false;
3178 : : }
3179 : : }
3180 [ # # ]: 0 : vMasterKey = vMasterKeyIn;
3181 : 0 : }
3182 : 0 : NotifyStatusChanged(this);
3183 : 0 : return true;
3184 : : }
3185 : :
3186 : 0 : std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
3187 : : {
3188 : 0 : std::set<ScriptPubKeyMan*> spk_mans;
3189 [ # # ]: 0 : for (bool internal : {false, true}) {
3190 [ # # ]: 0 : for (OutputType t : OUTPUT_TYPES) {
3191 [ # # ]: 0 : auto spk_man = GetScriptPubKeyMan(t, internal);
3192 [ # # ]: 0 : if (spk_man) {
3193 [ # # ]: 0 : spk_mans.insert(spk_man);
3194 : : }
3195 : : }
3196 : : }
3197 : 0 : return spk_mans;
3198 : 0 : }
3199 : :
3200 : 0 : bool CWallet::IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const
3201 : : {
3202 [ # # # # ]: 0 : for (const auto& [_, ext_spkm] : m_external_spk_managers) {
3203 [ # # ]: 0 : if (ext_spkm == &spkm) return true;
3204 : : }
3205 [ # # # # ]: 0 : for (const auto& [_, int_spkm] : m_internal_spk_managers) {
3206 [ # # ]: 0 : if (int_spkm == &spkm) return true;
3207 : : }
3208 : : return false;
3209 : : }
3210 : :
3211 : 1506 : std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
3212 : : {
3213 : 1506 : std::set<ScriptPubKeyMan*> spk_mans;
3214 [ + + ]: 13554 : for (const auto& spk_man_pair : m_spk_managers) {
3215 [ + - ]: 12048 : spk_mans.insert(spk_man_pair.second.get());
3216 : : }
3217 : 1506 : return spk_mans;
3218 : 0 : }
3219 : :
3220 : 3359 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
3221 : : {
3222 [ + + ]: 3359 : const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
3223 : 3359 : std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
3224 [ + - ]: 3359 : if (it == spk_managers.end()) {
3225 : : return nullptr;
3226 : : }
3227 : 3359 : return it->second;
3228 : : }
3229 : :
3230 : 108764 : std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script) const
3231 : : {
3232 [ + - ]: 108764 : std::set<ScriptPubKeyMan*> spk_mans;
3233 : :
3234 : : // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3235 [ + - ]: 108764 : const auto& it = m_cached_spks.find(script);
3236 [ + - ]: 108764 : if (it != m_cached_spks.end()) {
3237 [ + - ]: 108764 : spk_mans.insert(it->second.begin(), it->second.end());
3238 : : }
3239 : 108764 : SignatureData sigdata;
3240 [ + - + - ]: 217528 : Assume(std::all_of(spk_mans.begin(), spk_mans.end(), [&script, &sigdata](ScriptPubKeyMan* spkm) { return spkm->CanProvide(script, sigdata); }));
3241 : :
3242 : 108764 : return spk_mans;
3243 : 108764 : }
3244 : :
3245 : 0 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
3246 : : {
3247 [ # # ]: 0 : if (m_spk_managers.contains(id)) {
3248 : 0 : return m_spk_managers.at(id).get();
3249 : : }
3250 : : return nullptr;
3251 : : }
3252 : :
3253 : 285834 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
3254 : : {
3255 : 285834 : SignatureData sigdata;
3256 [ + - ]: 571668 : return GetSolvingProvider(script, sigdata);
3257 : 285834 : }
3258 : :
3259 : 285834 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
3260 : : {
3261 : : // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3262 : 285834 : const auto& it = m_cached_spks.find(script);
3263 [ + + ]: 285834 : if (it != m_cached_spks.end()) {
3264 : : // All spkms for a given script must already be able to make a SigningProvider for the script, so just return the first one.
3265 : 285486 : Assume(it->second.at(0)->CanProvide(script, sigdata));
3266 : 285486 : return it->second.at(0)->GetSolvingProvider(script);
3267 : : }
3268 : :
3269 : 348 : return nullptr;
3270 : : }
3271 : :
3272 : 0 : std::vector<WalletDescriptor> CWallet::GetWalletDescriptors(const CScript& script) const
3273 : : {
3274 : 0 : std::vector<WalletDescriptor> descs;
3275 [ # # # # ]: 0 : for (const auto spk_man: GetScriptPubKeyMans(script)) {
3276 [ # # # # ]: 0 : if (const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man)) {
3277 [ # # ]: 0 : LOCK(desc_spk_man->cs_desc_man);
3278 [ # # # # ]: 0 : descs.push_back(desc_spk_man->GetWalletDescriptor());
3279 : 0 : }
3280 : : }
3281 : 0 : return descs;
3282 : 0 : }
3283 : :
3284 : 9823 : void CWallet::AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man)
3285 : : {
3286 : : // Add spkm_man to m_spk_managers before calling any method
3287 : : // that might access it.
3288 : 9823 : const auto& spkm = m_spk_managers[id] = std::move(spkm_man);
3289 : :
3290 : : // Update birth time if needed
3291 : 9823 : MaybeUpdateBirthTime(spkm->GetTimeFirstKey());
3292 : 9823 : }
3293 : :
3294 : 0 : bool CWallet::WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const
3295 : : {
3296 : 0 : LOCK(cs_wallet);
3297 [ # # # # ]: 0 : return cb(vMasterKey);
3298 : 0 : }
3299 : :
3300 : 548238 : bool CWallet::HasEncryptionKeys() const
3301 : : {
3302 : 548238 : return !mapMasterKeys.empty();
3303 : : }
3304 : :
3305 : 0 : bool CWallet::HaveCryptedKeys() const
3306 : : {
3307 [ # # ]: 0 : for (const auto& spkm : GetAllScriptPubKeyMans()) {
3308 [ # # # # ]: 0 : if (spkm->HaveCryptedKeys()) return true;
3309 : : }
3310 : 0 : return false;
3311 : : }
3312 : :
3313 : 0 : void CWallet::ConnectScriptPubKeyManNotifiers()
3314 : : {
3315 [ # # ]: 0 : for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
3316 [ # # ]: 0 : spk_man->NotifyCanGetAddressesChanged.connect([this] {
3317 : 0 : NotifyCanGetAddressesChanged();
3318 : : });
3319 [ # # ]: 0 : spk_man->NotifyFirstKeyTimeChanged.connect([this](const ScriptPubKeyMan*, int64_t time) {
3320 : 0 : MaybeUpdateBirthTime(time);
3321 : : });
3322 : : }
3323 : 0 : }
3324 : :
3325 : 0 : void CWallet::LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc, const KeyMap& keys, const CryptedKeyMap& ckeys)
3326 : : {
3327 : 0 : std::unique_ptr<DescriptorScriptPubKeyMan> spk_manager;
3328 [ # # # # ]: 0 : if (IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
3329 [ # # ]: 0 : spk_manager = ExternalSignerScriptPubKeyMan::LoadFromStorage(*this, id, desc, m_keypool_size, keys, ckeys);
3330 : : } else {
3331 [ # # ]: 0 : spk_manager = DescriptorScriptPubKeyMan::LoadFromStorage(*this, id, desc, m_keypool_size, keys, ckeys);
3332 : : }
3333 [ # # ]: 0 : AddScriptPubKeyMan(id, std::move(spk_manager));
3334 : 0 : }
3335 : :
3336 : 0 : DescriptorScriptPubKeyMan& CWallet::SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal)
3337 : : {
3338 : 0 : AssertLockHeld(cs_wallet);
3339 [ # # ]: 0 : if (IsLocked()) {
3340 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
3341 : : }
3342 : 0 : auto spk_manager = DescriptorScriptPubKeyMan::GenerateNewSingleSig(*this, batch, m_keypool_size, master_key, output_type, internal);
3343 [ # # ]: 0 : DescriptorScriptPubKeyMan* out = spk_manager.get();
3344 [ # # ]: 0 : uint256 id = spk_manager->GetID();
3345 [ # # ]: 0 : AddScriptPubKeyMan(id, std::move(spk_manager));
3346 [ # # ]: 0 : AddActiveScriptPubKeyManWithDb(batch, id, output_type, internal);
3347 : 0 : return *out;
3348 : 0 : }
3349 : :
3350 : 0 : void CWallet::SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key)
3351 : : {
3352 : 0 : AssertLockHeld(cs_wallet);
3353 [ # # ]: 0 : for (bool internal : {false, true}) {
3354 [ # # ]: 0 : for (OutputType t : OUTPUT_TYPES) {
3355 : 0 : SetupDescriptorScriptPubKeyMan(batch, master_key, t, internal);
3356 : : }
3357 : : }
3358 : 0 : }
3359 : :
3360 : 0 : void CWallet::SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch)
3361 : : {
3362 : 0 : AssertLockHeld(cs_wallet);
3363 [ # # ]: 0 : assert(!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER));
3364 : : // Make a seed
3365 : 0 : CKey seed_key = GenerateRandomKey();
3366 [ # # ]: 0 : CPubKey seed = seed_key.GetPubKey();
3367 [ # # # # ]: 0 : assert(seed_key.VerifyPubKey(seed));
3368 : :
3369 : : // Get the extended key
3370 [ # # ]: 0 : CExtKey master_key;
3371 [ # # # # ]: 0 : master_key.SetSeed(seed_key);
3372 : :
3373 [ # # ]: 0 : SetupDescriptorScriptPubKeyMans(batch, master_key);
3374 : 0 : }
3375 : :
3376 : 0 : void CWallet::SetupDescriptorScriptPubKeyMans()
3377 : : {
3378 : 0 : AssertLockHeld(cs_wallet);
3379 : :
3380 [ # # ]: 0 : if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
3381 [ # # # # ]: 0 : if (!RunWithinTxn(GetDatabase(), /*process_desc=*/"setup descriptors", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet){
3382 : 0 : SetupOwnDescriptorScriptPubKeyMans(batch);
3383 : 0 : return true;
3384 [ # # ]: 0 : })) throw std::runtime_error("Error: cannot process db transaction for descriptors setup");
3385 : : } else {
3386 : 0 : auto signer = ExternalSignerScriptPubKeyMan::GetExternalSigner();
3387 [ # # # # : 0 : if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
# # ]
3388 : :
3389 : : // TODO: add account parameter
3390 : 0 : int account = 0;
3391 [ # # ]: 0 : UniValue signer_res = signer->GetDescriptors(account);
3392 : :
3393 [ # # # # : 0 : if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
# # ]
3394 : :
3395 [ # # ]: 0 : WalletBatch batch(GetDatabase());
3396 [ # # # # : 0 : if (!batch.TxnBegin()) throw std::runtime_error("Error: cannot create db transaction for descriptors import");
# # ]
3397 : :
3398 [ # # ]: 0 : for (bool internal : {false, true}) {
3399 [ # # # # ]: 0 : const UniValue& descriptor_vals = signer_res.find_value(internal ? "internal" : "receive");
3400 [ # # # # : 0 : if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
# # ]
3401 [ # # # # : 0 : for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
# # ]
3402 : 0 : const std::string& desc_str = desc_val.getValStr();
3403 : 0 : FlatSigningProvider keys;
3404 [ # # ]: 0 : std::string desc_error;
3405 [ # # # # ]: 0 : auto descs = Parse(desc_str, keys, desc_error, false);
3406 [ # # ]: 0 : if (descs.empty()) {
3407 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": Invalid descriptor \"" + desc_str + "\" (" + desc_error + ")");
# # # # ]
3408 : : }
3409 [ # # ]: 0 : auto& desc = descs.at(0);
3410 [ # # # # ]: 0 : if (!desc->GetOutputType()) {
3411 : 0 : continue;
3412 : : }
3413 [ # # ]: 0 : OutputType t = *desc->GetOutputType();
3414 [ # # ]: 0 : auto spk_manager = ExternalSignerScriptPubKeyMan::CreateNew(*this, batch, m_keypool_size, std::move(desc));
3415 [ # # ]: 0 : uint256 id = spk_manager->GetID();
3416 [ # # ]: 0 : AddScriptPubKeyMan(id, std::move(spk_manager));
3417 [ # # ]: 0 : AddActiveScriptPubKeyManWithDb(batch, id, t, internal);
3418 : 0 : }
3419 : : }
3420 : :
3421 : : // Ensure imported descriptors are committed to disk
3422 [ # # # # : 0 : if (!batch.TxnCommit()) throw std::runtime_error("Error: cannot commit db transaction for descriptors import");
# # ]
3423 : 0 : }
3424 : 0 : }
3425 : :
3426 : 0 : void CWallet::SetupWalletGeneration()
3427 : : {
3428 : 0 : AssertLockHeld(cs_wallet);
3429 : : // Skip setup for non-external-signer wallets that are either blank
3430 : : // or have private keys disabled (not having private keys implies blank).
3431 [ # # # # ]: 0 : if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER) &&
3432 [ # # ]: 0 : (IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET) || IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS))) {
3433 : 0 : return;
3434 : : }
3435 : 0 : SetupDescriptorScriptPubKeyMans();
3436 : : }
3437 : :
3438 : 16 : void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3439 : : {
3440 : 16 : WalletBatch batch(GetDatabase());
3441 [ + - ]: 16 : return AddActiveScriptPubKeyManWithDb(batch, id, type, internal);
3442 : 16 : }
3443 : :
3444 : 16 : void CWallet::AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal)
3445 : : {
3446 [ - + ]: 16 : if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
3447 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
3448 : : }
3449 : 16 : LoadActiveScriptPubKeyMan(id, type, internal);
3450 : 16 : }
3451 : :
3452 : 16 : void CWallet::LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3453 : : {
3454 : : // Activating ScriptPubKeyManager for a given output and change type is incompatible with legacy wallets.
3455 : : // Legacy wallets have only one ScriptPubKeyManager and it's active for all output and change types.
3456 : 16 : Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3457 : :
3458 [ + + + - ]: 24 : WalletLogPrintf("Setting spkMan to active: id = %s, type = %s, internal = %s", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3459 [ + + ]: 16 : auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3460 : 16 : auto& spk_mans_other = internal ? m_external_spk_managers : m_internal_spk_managers;
3461 : 16 : auto spk_man = m_spk_managers.at(id).get();
3462 : 16 : spk_mans[type] = spk_man;
3463 : :
3464 : 16 : const auto it = spk_mans_other.find(type);
3465 [ + + - + ]: 16 : if (it != spk_mans_other.end() && it->second == spk_man) {
3466 : 0 : spk_mans_other.erase(type);
3467 : : }
3468 : :
3469 : 16 : NotifyCanGetAddressesChanged();
3470 : 16 : }
3471 : :
3472 : 0 : void CWallet::DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
3473 : : {
3474 : 0 : auto spk_man = GetScriptPubKeyMan(type, internal);
3475 [ # # # # ]: 0 : if (spk_man != nullptr && spk_man->GetID() == id) {
3476 [ # # # # ]: 0 : WalletLogPrintf("Deactivate spkMan: id = %s, type = %s, internal = %s", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3477 : 0 : WalletBatch batch(GetDatabase());
3478 [ # # # # ]: 0 : if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type), internal)) {
3479 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": erasing active ScriptPubKeyMan id failed");
3480 : : }
3481 : :
3482 [ # # ]: 0 : auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3483 : 0 : spk_mans.erase(type);
3484 : 0 : }
3485 : :
3486 : 0 : NotifyCanGetAddressesChanged();
3487 : 0 : }
3488 : :
3489 : 8196 : DescriptorScriptPubKeyMan* CWallet::GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const
3490 : : {
3491 : 8196 : auto spk_man_pair = std::find_if(m_spk_managers.begin(), m_spk_managers.end(), [&desc](const auto& item) {
3492 [ + - ]: 201 : DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(item.second.get());
3493 [ + - + + ]: 201 : return spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc);
3494 : : });
3495 : :
3496 [ + + ]: 8196 : if (spk_man_pair != m_spk_managers.end()) {
3497 [ + - ]: 89 : return dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair->second.get());
3498 : : }
3499 : :
3500 : : return nullptr;
3501 : : }
3502 : :
3503 : 0 : std::optional<bool> CWallet::IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const
3504 : : {
3505 : : // only active ScriptPubKeyMan can be internal
3506 [ # # ]: 0 : if (!GetActiveScriptPubKeyMans().contains(spk_man)) {
3507 : 0 : return std::nullopt;
3508 : : }
3509 : :
3510 [ # # ]: 0 : const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
3511 [ # # ]: 0 : if (!desc_spk_man) {
3512 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": unexpected ScriptPubKeyMan type.");
3513 : : }
3514 : :
3515 : 0 : LOCK(desc_spk_man->cs_desc_man);
3516 [ # # # # ]: 0 : const auto& type = desc_spk_man->GetWalletDescriptor().descriptor->GetOutputType();
3517 [ # # ]: 0 : assert(type.has_value());
3518 : :
3519 [ # # # # ]: 0 : return GetScriptPubKeyMan(*type, /* internal= */ true) == desc_spk_man;
3520 : 0 : }
3521 : :
3522 : 8180 : util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
3523 : : {
3524 : 8180 : AssertLockHeld(cs_wallet);
3525 : :
3526 : 8180 : Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3527 : :
3528 : 8180 : auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3529 [ + + ]: 8180 : if (spk_man) {
3530 [ + - ]: 89 : WalletLogPrintf("Update existing descriptor: %s", desc.descriptor->ToString());
3531 [ - + ]: 89 : if (auto spkm_res = spk_man->UpdateWalletDescriptor(desc, signing_provider); !spkm_res) {
3532 [ # # ]: 0 : return util::Error{util::ErrorString(spkm_res)};
3533 : 89 : }
3534 : : } else {
3535 : 8091 : auto new_spk_man = DescriptorScriptPubKeyMan::CreateFromImport(*this, desc, m_keypool_size, signing_provider);
3536 [ + - ]: 8091 : spk_man = new_spk_man.get();
3537 : :
3538 : : // Save the descriptor to memory
3539 [ + - ]: 8091 : uint256 id = new_spk_man->GetID();
3540 [ + - ]: 8091 : AddScriptPubKeyMan(id, std::move(new_spk_man));
3541 : :
3542 : : // Write the existing cache to disk
3543 [ + - ]: 8091 : WalletBatch batch(GetDatabase());
3544 [ + - - + ]: 8091 : if (!batch.WriteDescriptorCacheItems(id, desc.cache)) {
3545 [ # # ]: 0 : return util::Error{_("Unable to write descriptor cache")};
3546 : : }
3547 : 8091 : }
3548 : :
3549 : : // Apply the label if necessary
3550 : : // Note: we disable labels for descriptors that are ranged or that don't produce output scripts (i.e. unused())
3551 [ + + + + ]: 8180 : if (!desc.descriptor->IsRange() && desc.descriptor->HasScripts()) {
3552 : 6114 : auto script_pub_keys = spk_man->GetScriptPubKeys();
3553 [ - + ]: 6114 : if (script_pub_keys.empty()) {
3554 [ # # ]: 0 : return util::Error{_("Could not generate scriptPubKeys (cache is empty)")};
3555 : : }
3556 : :
3557 [ + - ]: 6114 : if (!internal) {
3558 [ + + + - ]: 12431 : for (const auto& script : script_pub_keys) {
3559 : 6317 : CTxDestination dest;
3560 [ + + + - ]: 6317 : if (ExtractDestination(script, dest)) {
3561 [ + - ]: 2512 : SetAddressBook(dest, label, AddressPurpose::RECEIVE);
3562 : : }
3563 : 6317 : }
3564 : : }
3565 : 6114 : }
3566 : :
3567 : : // Save the descriptor to DB
3568 : 8180 : spk_man->WriteDescriptor();
3569 : :
3570 : : // Break balance caches so that outputs that are now IsMine in already known txs will be included in the balance
3571 : 8180 : MarkDirty();
3572 : :
3573 : 8180 : return std::reference_wrapper(*spk_man);
3574 : : }
3575 : :
3576 : 0 : util::Expected<CExtPubKey, WalletError> CWallet::AddHDKey(const std::optional<CExtKey>& key)
3577 : : {
3578 : 0 : LOCK(cs_wallet);
3579 : :
3580 [ # # # # ]: 0 : if (key && !key->key.IsValid()) {
3581 : 0 : return util::Unexpected{WalletError{
3582 : : WalletErrorCode::GenericError,
3583 [ # # ]: 0 : _("Invalid HD key"),
3584 : 0 : }};
3585 : : }
3586 : :
3587 [ # # # # ]: 0 : if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3588 : 0 : return util::Unexpected{WalletError{
3589 : : WalletErrorCode::GenericError,
3590 [ # # ]: 0 : _("addhdkey is not available for wallets without private keys")
3591 : 0 : }};
3592 : : }
3593 : :
3594 [ # # # # ]: 0 : if (IsLocked()) {
3595 : 0 : return util::Unexpected{WalletError{
3596 : : WalletErrorCode::UnlockNeeded,
3597 [ # # ]: 0 : _("Wallet needs to be unlocked to perform this operation.")
3598 : 0 : }};
3599 : : }
3600 : :
3601 [ # # ]: 0 : CExtKey hdkey;
3602 [ # # ]: 0 : if (key) {
3603 [ # # ]: 0 : hdkey = *key;
3604 : : } else {
3605 : 0 : CKey seed_key = GenerateRandomKey();
3606 [ # # # # ]: 0 : hdkey.SetSeed(seed_key);
3607 : 0 : }
3608 : :
3609 [ # # # # ]: 0 : std::string desc_str = "unused(" + EncodeExtKey(hdkey) + ")";
3610 : 0 : FlatSigningProvider keys;
3611 [ # # ]: 0 : std::string parse_error;
3612 [ # # # # ]: 0 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_error, /*require_checksum=*/false);
3613 [ # # ]: 0 : if (descs.empty()) {
3614 : 0 : return util::Unexpected{WalletError{
3615 : : WalletErrorCode::GenericError,
3616 [ # # ]: 0 : _("Invalid HD key")
3617 : 0 : }};
3618 : : }
3619 [ # # # # : 0 : WalletDescriptor w_desc(std::move(descs.at(0)), GetTime(), /*range_start=*/0, /*range_end=*/0, /*next_index=*/0);
# # # # ]
3620 : :
3621 [ # # # # ]: 0 : if (GetDescriptorScriptPubKeyMan(w_desc) != nullptr) {
3622 : 0 : return util::Unexpected{WalletError{
3623 : : WalletErrorCode::GenericError,
3624 [ # # ]: 0 : _("HD key already exists")
3625 : 0 : }};
3626 : : }
3627 : :
3628 [ # # # # ]: 0 : auto spkm = AddWalletDescriptor(w_desc, keys, /*label=*/"", /*internal=*/false);
3629 [ # # ]: 0 : if(!spkm) {
3630 [ # # ]: 0 : return util::Unexpected{WalletError{
3631 : : WalletErrorCode::GenericError,
3632 : : util::ErrorString(spkm),
3633 : 0 : }};
3634 : : }
3635 : :
3636 [ # # ]: 0 : const DescriptorScriptPubKeyMan& desc_spkm = spkm->get();
3637 [ # # ]: 0 : LOCK(desc_spkm.cs_desc_man);
3638 [ # # ]: 0 : std::set<CPubKey> pubkeys;
3639 : 0 : std::set<CExtPubKey> extpubs;
3640 [ # # # # ]: 0 : desc_spkm.GetWalletDescriptor().descriptor->GetPubKeys(pubkeys, extpubs);
3641 [ # # ]: 0 : Assume(pubkeys.empty());
3642 [ # # ]: 0 : Assume(extpubs.size() == 1);
3643 : :
3644 : 0 : return *extpubs.begin();
3645 [ # # ]: 0 : }
3646 : :
3647 : 109556 : bool CWallet::CanGrindR() const
3648 : : {
3649 : 109556 : return !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
3650 : : }
3651 : :
3652 : 39088 : void CWallet::CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
3653 : : {
3654 [ + + ]: 99630 : for (const auto& script : spks) {
3655 : 60542 : m_cached_spks[script].push_back(spkm);
3656 : : }
3657 : 39088 : }
3658 : :
3659 : 39088 : void CWallet::TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
3660 : : {
3661 : : // Update scriptPubKey cache
3662 : 39088 : CacheNewScriptPubKeys(spks, spkm);
3663 : 39088 : }
3664 : :
3665 : 0 : CWallet::HDPubKeyMap CWallet::GetHDPubKeys(HDKeyFilter filter) const
3666 : : {
3667 : 0 : AssertLockHeld(cs_wallet);
3668 : :
3669 : 0 : Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3670 : :
3671 [ # # ]: 0 : HDPubKeyMap xpubs;
3672 [ # # # # : 0 : for (const auto& spkm : filter == HDKeyFilter::Active ? GetActiveScriptPubKeyMans() : GetAllScriptPubKeyMans()) {
# # # # ]
3673 [ # # # # ]: 0 : auto* desc_spkm = Assert(dynamic_cast<DescriptorScriptPubKeyMan*>(spkm));
3674 [ # # ]: 0 : LOCK(desc_spkm->cs_desc_man);
3675 [ # # ]: 0 : WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();
3676 [ # # # # : 0 : if (filter == HDKeyFilter::UnusedKey && w_desc.descriptor->HasScripts()) continue;
# # ]
3677 : :
3678 [ # # ]: 0 : std::set<CPubKey> desc_pubkeys;
3679 : 0 : std::set<CExtPubKey> desc_xpubs;
3680 [ # # ]: 0 : w_desc.descriptor->GetPubKeys(desc_pubkeys, desc_xpubs);
3681 [ # # ]: 0 : for (const CExtPubKey& xpub : desc_xpubs) {
3682 [ # # # # ]: 0 : xpubs[xpub].insert(desc_spkm);
3683 : : }
3684 [ # # # # ]: 0 : }
3685 : 0 : return xpubs;
3686 : 0 : }
3687 : :
3688 : 0 : std::optional<CKey> CWallet::GetKey(const CKeyID& keyid) const
3689 : : {
3690 : 0 : Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
3691 : :
3692 [ # # ]: 0 : for (const auto& spkm : GetAllScriptPubKeyMans()) {
3693 [ # # ]: 0 : const DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
3694 [ # # ]: 0 : assert(desc_spkm);
3695 [ # # ]: 0 : LOCK(desc_spkm->cs_desc_man);
3696 [ # # # # ]: 0 : if (std::optional<CKey> key = desc_spkm->GetKey(keyid)) {
3697 [ # # ]: 0 : return key;
3698 [ # # ]: 0 : }
3699 : 0 : }
3700 : 0 : return std::nullopt;
3701 : : }
3702 : :
3703 : 0 : std::optional<CExtKey> CWallet::GetExtKey(const CExtPubKey& xpub) const
3704 : : {
3705 [ # # ]: 0 : if (std::optional<CKey> key = GetKey(xpub.pubkey.GetID())) {
3706 [ # # ]: 0 : return CExtKey{xpub, *key};
3707 : 0 : }
3708 : 0 : return std::nullopt;
3709 : : }
3710 : :
3711 : 11691 : void CWallet::WriteBestBlock() const
3712 : : {
3713 : 11691 : AssertLockHeld(cs_wallet);
3714 : :
3715 [ + - ]: 23382 : if (!m_last_block_processed.IsNull()) {
3716 : 11691 : CBlockLocator loc;
3717 [ + - ]: 11691 : chain().findBlock(m_last_block_processed, FoundBlock().locator(loc));
3718 : :
3719 [ + - ]: 11691 : if (!loc.IsNull()) {
3720 [ + - ]: 11691 : WalletBatch batch(GetDatabase());
3721 [ + - ]: 11691 : batch.WriteBestBlock(loc);
3722 : 11691 : }
3723 : 11691 : }
3724 : 11691 : }
3725 : :
3726 : 412565 : void CWallet::RefreshTXOsFromTx(const CWalletTx& wtx)
3727 : : {
3728 : 412565 : AssertLockHeld(cs_wallet);
3729 [ - + + - : 1650260 : for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); ++i) {
+ + ]
3730 [ + - + - ]: 412565 : const CTxOut& txout = wtx.GetTx()->vout.at(i);
3731 [ - + ]: 412565 : if (!IsMine(txout)) continue;
3732 : 412565 : COutPoint outpoint(wtx.GetHash(), i);
3733 [ + - ]: 412565 : if (m_txos.contains(outpoint)) {
3734 : : } else {
3735 : 412565 : m_txos.emplace(outpoint, WalletTXO{wtx, txout});
3736 : : }
3737 : : }
3738 : 412565 : }
3739 : :
3740 : 0 : void CWallet::RefreshAllTXOs()
3741 : : {
3742 : 0 : AssertLockHeld(cs_wallet);
3743 [ # # ]: 0 : for (const auto& [_, wtx] : mapWallet) {
3744 : 0 : RefreshTXOsFromTx(wtx);
3745 : : }
3746 : 0 : }
3747 : :
3748 : 0 : std::optional<WalletTXO> CWallet::GetTXO(const COutPoint& outpoint) const
3749 : : {
3750 : 0 : AssertLockHeld(cs_wallet);
3751 : 0 : const auto& it = m_txos.find(outpoint);
3752 [ # # ]: 0 : if (it == m_txos.end()) {
3753 : 0 : return std::nullopt;
3754 : : }
3755 : 0 : return it->second;
3756 : : }
3757 : :
3758 : 0 : void CWallet::DisconnectChainNotifications()
3759 : : {
3760 [ # # ]: 0 : if (m_chain_notifications_handler) {
3761 : 0 : m_chain_notifications_handler->disconnect();
3762 : 0 : chain().waitForNotifications();
3763 [ # # ]: 0 : m_chain_notifications_handler.reset();
3764 : : }
3765 : 0 : }
3766 : :
3767 : 0 : void CWallet::SetLastDecryptedFeatures(uint64_t features)
3768 : : {
3769 : 0 : AssertLockHeld(cs_wallet);
3770 : 0 : m_last_decrypted_features = features;
3771 : 0 : }
3772 : : } // namespace wallet
|