Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2021 The Bitcoin Core developers
3 : // Copyright (c) 2014-2025 The Dash Core developers
4 : // Distributed under the MIT software license, see the accompanying
5 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 :
7 : #ifndef BITCOIN_WALLET_WALLET_H
8 : #define BITCOIN_WALLET_WALLET_H
9 :
10 : #include <consensus/amount.h>
11 : #include <fs.h>
12 : #include <governance/common.h>
13 : #include <interfaces/chain.h>
14 : #include <interfaces/coinjoin.h>
15 : #include <interfaces/handler.h>
16 : #include <policy/feerate.h>
17 : #include <psbt.h>
18 : #include <saltedhasher.h>
19 : #include <tinyformat.h>
20 : #include <util/hasher.h>
21 : #include <util/message.h>
22 : #include <util/result.h>
23 : #include <util/string.h>
24 : #include <util/system.h>
25 : #include <util/strencodings.h>
26 : #include <util/ui_change_type.h>
27 : #include <validationinterface.h>
28 : #include <wallet/crypter.h>
29 : #include <wallet/coinselection.h>
30 : #include <external_signer.h>
31 : #include <wallet/scriptpubkeyman.h>
32 : #include <wallet/transaction.h>
33 : #include <wallet/walletdb.h>
34 : #include <wallet/walletutil.h>
35 :
36 : #include <algorithm>
37 : #include <atomic>
38 : #include <map>
39 : #include <memory>
40 : #include <optional>
41 : #include <set>
42 : #include <stdexcept>
43 : #include <stdint.h>
44 : #include <string>
45 : #include <unordered_set>
46 : #include <utility>
47 : #include <unordered_map>
48 : #include <vector>
49 :
50 : #include <boost/signals2/signal.hpp>
51 :
52 : class CKey;
53 : class CScript;
54 : class CTxDSIn;
55 : enum class FeeEstimateMode;
56 : struct bilingual_str;
57 :
58 : using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
59 :
60 : namespace wallet {
61 : struct WalletContext;
62 :
63 : //! Explicitly unload and delete the wallet.
64 : // Blocks the current thread after signaling the unload intent so that all
65 : // wallet pointer owners release the wallet.
66 : // Note that, when blocking is not required, the wallet is implicitly unloaded
67 : // by the shared pointer deleter.
68 : void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
69 :
70 : bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
71 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
72 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
73 : std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
74 : std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
75 : std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
76 : 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);
77 : 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);
78 : 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);
79 : std::unique_ptr<interfaces::Handler> HandleLoadWalletLoading(WalletContext& context, LoadWalletFn load_wallet);
80 : std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
81 : void NotifyWalletLoading(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
82 : void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
83 : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
84 :
85 : //! -paytxfee default
86 : constexpr CAmount DEFAULT_PAY_TX_FEE = 0;
87 : //! -fallbackfee default
88 : static const CAmount DEFAULT_FALLBACK_FEE = 1000;
89 : //! -discardfee default
90 : static const CAmount DEFAULT_DISCARD_FEE = 10000;
91 : //! -mintxfee default
92 : static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
93 : //! -consolidatefeerate default
94 : static const CAmount DEFAULT_CONSOLIDATE_FEERATE{1000}; // 10 sat/vbyte
95 : /**
96 : * maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled by default
97 : *
98 : * A value of -1 disables this feature completely.
99 : * A value of 0 (current default) means to attempt to do partial spend avoidance, and use its results if the fees remain *unchanged*
100 : * A value > 0 means to do partial spend avoidance if the fee difference against a regular coin selection instance is in the range [0..value].
101 : */
102 : static const CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE = 0;
103 : //! discourage APS fee higher than this amount
104 : constexpr CAmount HIGH_APS_FEE{COIN / 10000};
105 : //! Default for -spendzeroconfchange
106 : static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
107 : //! Default for -walletrejectlongchains
108 : static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
109 : //! -txconfirmtarget default
110 : static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
111 : static const bool DEFAULT_WALLETBROADCAST = true;
112 : static const bool DEFAULT_DISABLE_WALLET = false;
113 : static const bool DEFAULT_WALLETCROSSCHAIN = false;
114 : //! -dustprotectionthreshold default (0 = disabled)
115 : static constexpr CAmount DEFAULT_DUST_PROTECTION_THRESHOLD{0};
116 : //! -dustprotectionthreshold maximum (matches GUI spinbox cap)
117 : static constexpr CAmount MAX_DUST_PROTECTION_THRESHOLD{1000000};
118 : //! -maxtxfee default
119 : static const CAmount DEFAULT_TRANSACTION_MAXFEE = COIN / 10;
120 : //! Discourage users to set fees higher than this amount (in satoshis) per kB
121 : static const CAmount HIGH_TX_FEE_PER_KB = COIN / 100;
122 : //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
123 : static const CAmount HIGH_MAX_TX_FEE = 100 * HIGH_TX_FEE_PER_KB;
124 : //! Pre-calculated constants for input size estimation in *virtual size*
125 : static constexpr size_t DUMMY_NESTED_P2PKH_INPUT_SIZE = 113;
126 : //! if set, all keys will be derived by using BIP39/BIP44
127 : static const bool DEFAULT_USE_HD_WALLET = true;
128 :
129 : class CCoinControl;
130 : class CWalletTx;
131 : class ReserveDestination;
132 :
133 : extern RecursiveMutex cs_main;
134 :
135 : /** (client) version numbers for particular wallet features */
136 : struct CompactTallyItem
137 : {
138 : CTxDestination txdest;
139 5 : CAmount nAmount{0};
140 : std::vector<COutPoint> outpoints;
141 15 : CompactTallyItem() = default;
142 : };
143 :
144 : static constexpr uint64_t KNOWN_WALLET_FLAGS =
145 : WALLET_FLAG_AVOID_REUSE
146 : | WALLET_FLAG_BLANK_WALLET
147 : | WALLET_FLAG_KEY_ORIGIN_METADATA
148 : | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
149 : | WALLET_FLAG_DISABLE_PRIVATE_KEYS
150 : | WALLET_FLAG_DESCRIPTORS
151 : | WALLET_FLAG_EXTERNAL_SIGNER;
152 :
153 : static constexpr uint64_t MUTABLE_WALLET_FLAGS =
154 : WALLET_FLAG_AVOID_REUSE;
155 :
156 : static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
157 : {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
158 : {"blank", WALLET_FLAG_BLANK_WALLET},
159 : {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
160 : {"last_hardened_xpub_cached", WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
161 : {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
162 : {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
163 : {"external_signer", WALLET_FLAG_EXTERNAL_SIGNER}
164 : };
165 :
166 : extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
167 :
168 : /** A wrapper to reserve an address from a wallet
169 : *
170 : * ReserveDestination is used to reserve an address. It is passed around
171 : * during the CreateTransaction/CommitTransaction procedure.
172 : *
173 : * Instantiating a ReserveDestination does not reserve an address. To do so,
174 : * GetReservedDestination() needs to be called on the object. Once an address has been
175 : * reserved, call KeepDestination() on the ReserveDestination object to make sure it is not
176 : * returned. Call ReturnDestination() to return the address so it can be reused (for
177 : * example, if the address was used in a new transaction
178 : * and that transaction was not completed and needed to be aborted).
179 : *
180 : * If an address is reserved and KeepDestination() is not called, then the address will be
181 : * returned when the ReserveDestination goes out of scope.
182 : */
183 : class ReserveDestination
184 : {
185 : protected:
186 : //! The wallet to reserve from
187 : const CWallet* const pwallet;
188 : //! The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called
189 14664 : ScriptPubKeyMan* m_spk_man{nullptr};
190 :
191 : //! The index of the address's key in the keypool
192 14664 : int64_t nIndex{-1};
193 : //! The destination
194 : CTxDestination address;
195 : //! Whether this is from the internal (change output) keypool
196 14664 : bool fInternal{false};
197 :
198 : public:
199 : //! Construct a ReserveDestination object. This does NOT reserve an address yet
200 43992 : explicit ReserveDestination(CWallet* pwallet)
201 14664 : : pwallet(pwallet)
202 29328 : { }
203 :
204 : ReserveDestination(const ReserveDestination&) = delete;
205 : ReserveDestination& operator=(const ReserveDestination&) = delete;
206 :
207 : //! Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool
208 29328 : ~ReserveDestination()
209 14664 : {
210 14664 : ReturnDestination();
211 29328 : }
212 :
213 : //! Reserve an address
214 : util::Result<CTxDestination> GetReservedDestination(bool internal);
215 : //! Return reserved address
216 : void ReturnDestination();
217 : //! Keep the address. Do not return its key to the keypool when this object goes out of scope
218 : void KeepDestination();
219 : };
220 :
221 : /** Address book data */
222 : class CAddressBookData
223 : {
224 : private:
225 46823 : bool m_change{true};
226 : std::string m_label;
227 : public:
228 : std::string purpose;
229 :
230 140469 : CAddressBookData() : purpose("unknown") {}
231 :
232 : /**
233 : * Whether coins with this address have previously been spent. Set when the
234 : * the wallet avoid_reuse option is enabled and this is an IsMine address
235 : * that has already received funds and spent them. This is used during coin
236 : * selection to increase privacy by not creating different transactions
237 : * that spend from the same addresses.
238 : */
239 46823 : bool previously_spent{false};
240 :
241 : /**
242 : * Map containing data about previously generated receive requests
243 : * requesting funds to be sent to this address. Only present for IsMine
244 : * addresses. Map keys are decimal numbers uniquely identifying each
245 : * request, and map values are serialized RecentRequestEntry objects
246 : * containing BIP21 URI information including message and amount.
247 : */
248 46823 : std::map<std::string, std::string> receive_requests{};
249 :
250 37077 : bool IsChange() const { return m_change; }
251 34912 : const std::string& GetLabel() const { return m_label; }
252 47164 : void SetLabel(const std::string& label) {
253 47164 : m_change = false;
254 47164 : m_label = label;
255 47164 : }
256 : };
257 :
258 : struct CRecipient
259 : {
260 : CScript scriptPubKey;
261 : CAmount nAmount;
262 : bool fSubtractFeeFromAmount;
263 : };
264 :
265 : struct WalletTxHasher
266 : {
267 : StaticSaltedHasher h;
268 1889266 : size_t operator()(const CWalletTx* a) const
269 : {
270 1889266 : return h(a->GetHash());
271 : }
272 : };
273 :
274 : /** Status of a wallet rescan operation */
275 : enum class RescanStatus : uint8_t {
276 : BUSY, //!< Wallet is already rescanning
277 : FAILURE, //!< Rescan failed
278 : SUCCESS, //!< Rescan completed successfully
279 : USER_ABORT, //!< User aborted the rescan
280 : };
281 :
282 : class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
283 : /**
284 : * A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.
285 : */
286 : class CWallet final : public WalletStorage, public interfaces::Chain::Notifications
287 : {
288 : private:
289 : CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
290 :
291 : //! if fOnlyMixingAllowed is true, only mixing should be allowed in unlocked wallet
292 2371 : bool fOnlyMixingAllowed{false};
293 :
294 : bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool fForMixingOnly = false);
295 :
296 2371 : std::atomic<bool> fAbortRescan{false}; // reset by WalletRescanReserver::reserve()
297 2371 : std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
298 2371 : std::atomic<bool> m_attaching_chain{false};
299 2371 : std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
300 2371 : std::atomic<double> m_scanning_progress{0};
301 : friend class WalletRescanReserver;
302 :
303 : //! the current wallet version: clients below this version are not able to load the wallet
304 2371 : int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
305 :
306 : /** The next scheduled rebroadcast of wallet transactions. */
307 2371 : std::atomic<int64_t> m_next_resend{};
308 : /** Whether this wallet will submit newly created transactions to the node's mempool and
309 : * prompt rebroadcasts (see ResendWalletTransactions()). */
310 2371 : bool fBroadcastTransactions = false;
311 : // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
312 2371 : std::atomic<int64_t> m_best_block_time {0};
313 :
314 2371 : mutable bool fAnonymizableTallyCached = false;
315 : mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached;
316 2371 : mutable bool fAnonymizableTallyCachedNonDenom = false;
317 : mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom;
318 :
319 : /**
320 : * Used to keep track of spent outpoints, and
321 : * detect and report conflicts (double-spends or
322 : * mutated transactions where the mutant gets mined).
323 : */
324 : typedef std::unordered_multimap<COutPoint, uint256, SaltedOutpointHasher> TxSpends;
325 : TxSpends mapTxSpends GUARDED_BY(cs_wallet);
326 : void AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
327 : void AddToSpends(const CWalletTx& wtx, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
328 :
329 : std::set<COutPoint> setWalletUTXO;
330 : /** Add new UTXOs to the wallet UTXO set
331 : *
332 : * @param[in] tx Transaction to scan eligible UTXOs from
333 : * @param[in] ret_dups Allow UTXOs already in set to be included in return value
334 : * @returns Set of all new UTXOs (eligible to be) added to set */
335 : std::set<COutPoint> AddWalletUTXOs(CTransactionRef tx, bool ret_dups) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
336 : mutable std::map<COutPoint, int> mapOutpointRoundsCache GUARDED_BY(cs_wallet);
337 :
338 : /**
339 : * Add a transaction to the wallet, or update it. confirm.block_* should
340 : * be set when the transaction was known to be included in a block. When
341 : * block_hash.IsNull(), then wallet state is not updated in AddToWallet, but
342 : * notifications happen and cached balances are marked dirty.
343 : *
344 : * If fUpdate is true, existing transactions will be updated.
345 : * TODO: One exception to this is that the abandoned state is cleared under the
346 : * assumption that any further notification of a transaction that was considered
347 : * abandoned is an indication that it is not safe to be considered abandoned.
348 : * Abandoned state should probably be more carefully tracked via different
349 : * chain notifications or by checking mempool presence when necessary.
350 : *
351 : * Should be called with rescanning_old_block set to true, if the transaction is
352 : * not discovered in real time, but during a rescan of old blocks.
353 : */
354 : bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, WalletBatch& batch, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
355 :
356 : /** Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
357 : void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
358 :
359 : enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
360 :
361 : using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
362 :
363 : /** Mark a transaction (and its in-wallet descendants) as a particular tx state. */
364 : void RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
365 :
366 : /** Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
367 : void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
368 :
369 : void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
370 :
371 : void SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, WalletBatch& batch, bool update_tx = true, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
372 :
373 : /** WalletFlags set on this wallet. */
374 2371 : std::atomic<uint64_t> m_wallet_flags{0};
375 :
376 : bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
377 :
378 : //! Unsets a wallet flag and saves it to disk
379 : void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
380 :
381 : //! Unset the blank wallet flag and saves it to disk
382 : void UnsetBlankWalletFlag(WalletBatch& batch) override;
383 :
384 : // Reset coinjoin and reset key counter
385 : void NewKeyPoolCallback() override;
386 :
387 : // Decreases amount of nKeysLeftSinceAutoBackup after KeepDestination
388 : void KeepDestinationCallback(bool erased) override;
389 :
390 : /** Provider of aplication-wide arguments. */
391 : const ArgsManager& m_args;
392 :
393 : /** Interface for accessing chain state. */
394 : interfaces::Chain* m_chain;
395 :
396 : /** Interface for accessing CoinJoin state. */
397 : interfaces::CoinJoin::Loader* m_coinjoin_loader;
398 :
399 : /** Wallet name: relative directory name or "" for default wallet. */
400 : std::string m_name;
401 :
402 : /** Internal database handle. */
403 : std::unique_ptr<WalletDatabase> m_database;
404 :
405 : /**
406 : * The following is used to keep track of how far behind the wallet is
407 : * from the chain sync, and to allow clients to block on us being caught up.
408 : *
409 : * Processed hash is a pointer on node's tip and doesn't imply that the wallet
410 : * has scanned sequentially all blocks up to this one.
411 : */
412 : uint256 m_last_block_processed GUARDED_BY(cs_wallet);
413 :
414 : /** Pulled from wallet DB ("cj_salt") and used when mixing a random number of rounds.
415 : * This salt is needed to prevent an attacker from learning how many extra times
416 : * the input was mixed based only on information in the blockchain.
417 : */
418 : uint256 nCoinJoinSalt;
419 :
420 : /**
421 : * Populates nCoinJoinSalt with value from database (and migrates salt stored with legacy key).
422 : */
423 : void InitCJSaltFromDb();
424 :
425 : /** Height of last block processed is used by wallet to know depth of transactions
426 : * without relying on Chain interface beyond asynchronous updates. For safety, we
427 : * initialize it to -1. Height is a pointer on node's tip and doesn't imply
428 : * that the wallet has scanned sequentially all blocks up to this one.
429 : */
430 2371 : int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
431 :
432 2371 : ScriptPubKeyMan* m_external_spk_managers{nullptr};
433 2371 : ScriptPubKeyMan* m_internal_spk_managers{nullptr};
434 :
435 : // Indexed by a unique identifier produced by each ScriptPubKeyMan using
436 : // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
437 : std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
438 :
439 : /**
440 : * Catch wallet up to current chain, scanning new blocks, updating the best
441 : * block locator and m_last_block_processed, and registering for
442 : * notifications about new blocks and transactions.
443 : */
444 : static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings);
445 :
446 : public:
447 : /**
448 : * Main wallet lock.
449 : * This lock protects all the fields added by CWallet.
450 : */
451 : mutable RecursiveMutex cs_wallet;
452 :
453 510493 : WalletDatabase& GetDatabase() const override
454 : {
455 510493 : assert(static_cast<bool>(m_database));
456 510493 : return *m_database;
457 : }
458 :
459 : /** Get a name for this wallet for logging/debugging purposes.
460 : */
461 560379 : const std::string& GetName() const { return m_name; }
462 :
463 : /**
464 : * Get an existing CoinJoin salt. Will attempt to read database (and migrate legacy salts) if
465 : * nCoinJoinSalt is empty but will skip database read if nCoinJoinSalt is populated.
466 : **/
467 : const uint256& GetCoinJoinSalt();
468 :
469 : /**
470 : * Write a new CoinJoin salt. This will directly write the new salt value into the wallet database.
471 : * Ensuring that undesirable behaviour like overwriting the salt of a wallet that already uses CoinJoin
472 : * is the responsibility of the caller.
473 : **/
474 : bool SetCoinJoinSalt(const uint256& cj_salt);
475 :
476 : // Map from governance object hash to governance object, they are added by gobject_prepare.
477 : std::map<uint256, Governance::Object> m_gobjects;
478 :
479 : typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
480 : MasterKeyMap mapMasterKeys;
481 2371 : unsigned int nMasterKeyMaxID = 0;
482 :
483 : /** Construct wallet with specified name and database implementation. */
484 11855 : CWallet(interfaces::Chain* chain, interfaces::CoinJoin::Loader* coinjoin_loader, const std::string& name, const ArgsManager& args, std::unique_ptr<WalletDatabase> database)
485 2371 : : m_args(args),
486 2371 : m_chain(chain),
487 2371 : m_coinjoin_loader(coinjoin_loader),
488 2371 : m_name(name),
489 2371 : m_database(std::move(database))
490 7113 : {
491 4742 : }
492 :
493 4742 : ~CWallet()
494 2371 : {
495 : // Should not have slots connected at this point.
496 2371 : assert(NotifyUnload.empty());
497 4742 : }
498 :
499 : /** Interface to assert chain access */
500 48704 : bool HaveChain() const { return m_chain ? true : false; }
501 : bool IsCrypted() const;
502 : bool IsLocked(bool fForMixing = false) const override;
503 : bool Lock(bool fForMixing = false);
504 :
505 : void UpdateProgress(const std::string& title, int nProgress) override;
506 :
507 : /* A helper function which loops through wallet UTXOs */
508 : std::unordered_set<const CWalletTx*, WalletTxHasher> GetSpendableTXs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
509 :
510 : /** Map from txid to CWalletTx for all transactions this wallet is
511 : * interested in, including received and sent transactions. */
512 : std::unordered_map<uint256, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
513 :
514 : typedef std::multimap<int64_t, CWalletTx*> TxItems;
515 : TxItems wtxOrdered;
516 :
517 2371 : int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
518 :
519 : std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
520 : const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
521 :
522 : /** Set of Coins owned by this wallet that we won't try to spend from. A
523 : * Coin may be locked if it has already been used to fund a transaction
524 : * that hasn't confirmed yet. We wouldn't consider the Coin spent already,
525 : * but also shouldn't try to use it again. */
526 : std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
527 :
528 : int64_t nKeysLeftSinceAutoBackup;
529 :
530 : /** Registered interfaces::Chain::Notifications handler. */
531 : std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
532 :
533 : /** Interface for accessing chain state. */
534 5814687 : interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
535 :
536 : /** Interface for accessing CoinJoin state. */
537 6829 : interfaces::CoinJoin::Loader& coinjoin_loader() { assert(m_coinjoin_loader); return *m_coinjoin_loader; }
538 : /** Interface for availability status of CoinJoin. */
539 6831 : bool coinjoin_available() { return m_coinjoin_loader != nullptr; }
540 :
541 : const CWalletTx* GetWalletTx(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
542 :
543 : std::set<uint256> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
544 :
545 : /**
546 : * Return depth of transaction in blockchain:
547 : * <0 : conflicts with a transaction this deep in the blockchain
548 : * 0 : in memory pool, waiting to be included in a block
549 : * >=1 : this many blocks deep in the main chain
550 : */
551 : int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
552 238824 : bool IsTxInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
553 : {
554 238824 : AssertLockHeld(cs_wallet);
555 238824 : return GetTxDepthInMainChain(wtx) > 0;
556 : }
557 :
558 : bool IsTxLockedByInstantSend(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
559 : bool IsTxChainLocked(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
560 :
561 : /**
562 : * @return number of blocks to maturity for this transaction:
563 : * 0 : is not a coinbase transaction, or is a mature coinbase transaction
564 : * >0 : is a coinbase transaction which matures in this many blocks
565 : */
566 : int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
567 : bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
568 :
569 : //! check whether we support the named feature
570 42909 : bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
571 :
572 : // Coin selection
573 : bool SelectTxDSInsByDenomination(int nDenom, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet);
574 : bool SelectDenominatedAmounts(CAmount nValueMax, std::set<CAmount>& setAmountsRet) const;
575 :
576 : std::vector<CompactTallyItem> SelectCoinsGroupedByAddresses(bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true, int nMaxOupointsPerAddress = -1) const;
577 :
578 : bool HasCollateralInputs(bool fOnlyConfirmed = true) const;
579 : int CountInputsWithAmount(CAmount nInputAmount) const;
580 :
581 : // get the CoinJoin chain depth for a given input
582 : int GetRealOutpointCoinJoinRounds(const COutPoint& outpoint, int nRounds = 0) const;
583 : // respect current settings
584 : int GetCappedOutpointCoinJoinRounds(const COutPoint& outpoint) const;
585 : // drop the internal cache to let Get...Rounds recalculate CJ balance from scratch and notify UI
586 : void ClearCoinJoinRoundsCache();
587 :
588 : bool IsDenominated(const COutPoint& outpoint) const;
589 : bool IsFullyMixed(const COutPoint& outpoint) const;
590 :
591 : bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
592 :
593 : // Whether this or any known UTXO with the same single key has been spent.
594 : bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
595 : void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
596 :
597 : void RecalculateMixedCredit(const uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
598 :
599 : /** Display address on an external signer. Returns false if external signer support is not compiled */
600 : bool DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
601 :
602 : bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
603 : bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
604 : bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
605 : bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
606 : const std::set<COutPoint>& ListLockedCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
607 : std::vector<COutPoint> ListProTxCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
608 : std::vector<COutPoint> ListProTxCoins(const std::set<COutPoint>& utxos) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
609 : void LockProTxCoins(const std::set<COutPoint>& utxos, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
610 :
611 : /** Returns true if the given output of a wallet transaction is a dust protection target:
612 : * value is in (0, threshold], tx is normal type, not coinbase, and not from this wallet. */
613 : bool IsDustProtectionTarget(const CWalletTx& wtx, unsigned int output_index) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
614 : /** Lock dust outputs in a specific transaction if dust protection is enabled. */
615 : void CheckAndLockDustOutputs(const uint256& txHash, WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
616 : /** Lock all existing dust UTXOs if dust protection is enabled. Called on wallet load. */
617 : void LockExistingDustOutputs() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
618 :
619 : /*
620 : * Rescan abort properties
621 : */
622 0 : void AbortRescan() { fAbortRescan = true; }
623 1182 : bool IsAbortingRescan() const { return fAbortRescan; }
624 2076 : bool IsScanning() const { return fScanningWallet; }
625 0 : SteadyClock::duration ScanningDuration() const { return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
626 0 : double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
627 :
628 : //! Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo
629 : void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
630 :
631 : //! Upgrade DescriptorCaches
632 : void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
633 :
634 1083 : bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
635 :
636 : //! Marks destination as previously spent.
637 : void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
638 : //! Appends payment request to destination.
639 : void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
640 :
641 : //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
642 2371 : int64_t nRelockTime GUARDED_BY(cs_wallet){0};
643 :
644 : // Used to prevent concurrent calls to walletpassphrase RPC.
645 : Mutex m_unlock_mutex;
646 : bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false);
647 : bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
648 : bool EncryptWallet(const SecureString& strWalletPassphrase);
649 :
650 : void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
651 : unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
652 :
653 : /**
654 : * Increment the next transaction order id
655 : * @return next transaction order id
656 : */
657 : int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
658 : DBErrors ReorderTransactions();
659 :
660 : void MarkDirty();
661 :
662 : //! Callback for updating transaction metadata in mapWallet.
663 : //!
664 : //! @param wtx - reference to mapWallet transaction to update
665 : //! @param new_tx - true if wtx is newly inserted, false if it previously existed
666 : //!
667 : //! @return true if wtx is changed and needs to be saved to disk, otherwise false
668 : using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
669 :
670 : /**
671 : * Add the transaction to the wallet, wrapping it up inside a CWalletTx
672 : * @return the recently added wtx pointer or nullptr if there was a db write error.
673 : */
674 : CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
675 : bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
676 : void transactionAddedToMempool(const CTransactionRef& tx, int64_t nAcceptTime) override;
677 : void blockConnected(const CBlock& block, int height) override;
678 : void blockDisconnected(const CBlock& block, int height) override;
679 : void updatedBlockTip() override;
680 : int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
681 :
682 1498 : struct ScanResult {
683 1498 : enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
684 :
685 : //! Hash and height of most recent block that was successfully scanned.
686 : //! Unset if no blocks were scanned due to read errors or the chain
687 : //! being empty.
688 : uint256 last_scanned_block;
689 : std::optional<int> last_scanned_height;
690 :
691 : //! Height of the most recent block that could not be scanned due to
692 : //! read errors or pruning. Will be set if status is FAILURE, unset if
693 : //! status is SUCCESS, and may or may not be set if status is
694 : //! USER_ABORT.
695 : uint256 last_failed_block;
696 : };
697 : ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress);
698 : void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
699 : void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
700 : void ResendWalletTransactions();
701 :
702 : CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const;
703 : float GetAverageAnonymizedRounds() const;
704 : CAmount GetNormalizedAnonymizedBalance() const;
705 :
706 : /** Fetch the inputs and sign with SIGHASH_ALL. */
707 : bool SignTransaction(CMutableTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
708 : /** Sign the tx given the input coins and sighash. */
709 : bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
710 : SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
711 : /** Sign the payload of special transaction.
712 : * Because wallet is not aware about special transactions entity,
713 : * but it should work for any its type, we pass there directly a hash of payload.
714 : */
715 : bool SignSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) const;
716 : /**
717 : * Sign a governance vote using wallet signing methods.
718 : *
719 : * @param[in] keyID The key ID to use for signing
720 : * @param[in,out] vote The governance vote to sign (signature is set on success)
721 : * @return true if signing succeeded, false otherwise
722 : */
723 : bool SignGovernanceVote(const CKeyID& keyID, CGovernanceVote& vote) const;
724 :
725 : /**
726 : * Fills out a PSBT with information from the wallet. Fills in UTXOs if we have
727 : * them. Tries to sign if sign=true. Sets `complete` if the PSBT is now complete
728 : * (i.e. has all required signatures or signature-parts, and is ready to
729 : * finalize.) Sets `error` and returns false if something goes wrong.
730 : *
731 : * @param[in] psbtx PartiallySignedTransaction to fill in
732 : * @param[out] complete indicates whether the PSBT is now complete
733 : * @param[in] sighash_type the sighash type to use when signing (if PSBT does not specify)
734 : * @param[in] sign whether to sign or not
735 : * @param[in] bip32derivs whether to fill in bip32 derivation information if available
736 : * @param[out] n_signed the number of inputs signed by this wallet
737 : * @param[in] finalize whether to create the final scriptSig
738 : * return error
739 : */
740 : TransactionError FillPSBT(PartiallySignedTransaction& psbtx,
741 : bool& complete,
742 : int sighash_type = 1 /* SIGHASH_ALL */,
743 : bool sign = true,
744 : bool bip32derivs = true,
745 : size_t* n_signed = nullptr,
746 : bool finalize = true) const;
747 :
748 : /**
749 : * Submit the transaction to the node's mempool and then relay to peers.
750 : * Should be called after CreateTransaction unless you want to abort
751 : * broadcasting the transaction.
752 : *
753 : * @param[in] tx The transaction to be broadcast.
754 : * @param[in] mapValue key-values to be set on the transaction.
755 : * @param[in] orderForm BIP 70 / BIP 21 order form details to be set on the transaction.
756 : */
757 : void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
758 :
759 : /** Will SubmitTxMemoryPoolAndRelay() consider wtx if supplied */
760 : bool CanTxBeResent(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
761 : /** Pass this transaction to node for mempool insertion and relay to peers if flag set to true */
762 : bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, bilingual_str& err_string, bool relay) const
763 : EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
764 :
765 : bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const
766 : {
767 : std::vector<CTxOut> v_txouts(txouts.size());
768 : std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
769 : return DummySignTx(txNew, v_txouts, coin_control);
770 : }
771 : bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const;
772 :
773 : bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
774 : bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
775 : bool ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
776 : bool ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
777 :
778 2371 : CFeeRate m_pay_tx_fee{DEFAULT_PAY_TX_FEE};
779 2371 : unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
780 : /** Allow Coin Selection to pick unconfirmed UTXOs that were sent from our own wallet if it
781 : * cannot fund the transaction otherwise. */
782 2371 : bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
783 2371 : bool m_allow_fallback_fee{true}; //!< will be false if -fallbackfee=0
784 2371 : CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE}; //!< Override with -mintxfee
785 : /**
786 : * If fee estimation does not have enough data to provide estimates, use this fee instead.
787 : * Has no effect if not using fee estimation
788 : * Override with -fallbackfee
789 : */
790 2371 : CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
791 :
792 : /** If the cost to spend a change output at this feerate is greater than the value of the
793 : * output itself, just drop it to fees. */
794 2371 : CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
795 :
796 : /** When the actual feerate is less than the consolidate feerate, we will tend to make transactions which
797 : * consolidate inputs. When the actual feerate is greater than the consolidate feerate, we will tend to make
798 : * transactions which have the lowest fees.
799 : */
800 2371 : CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
801 :
802 : /** The maximum fee amount we're willing to pay to prioritize partial spend avoidance. */
803 2371 : CAmount m_max_aps_fee{DEFAULT_MAX_AVOIDPARTIALSPEND_FEE}; //!< note: this is absolute fee, not fee rate
804 : /** Absolute maximum transaction fee (in satoshis) used by default for the wallet */
805 2371 : CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
806 :
807 : /** Dust protection threshold in duffs. UTXOs from external transactions at or below this value
808 : * are automatically locked to prevent dust attacks. 0 = disabled. Override with -dustprotectionthreshold. */
809 2371 : CAmount m_dust_protection_threshold{DEFAULT_DUST_PROTECTION_THRESHOLD};
810 :
811 : size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
812 : bool TopUpKeyPool(unsigned int kpSize = 0);
813 :
814 : std::optional<int64_t> GetOldestKeyPoolTime() const;
815 :
816 : // Filter struct for 'ListAddrBookAddresses'
817 0 : struct AddrBookFilter {
818 : // Fetch addresses with the provided label
819 0 : std::optional<std::string> m_op_label{std::nullopt};
820 : // Don't include change addresses by default
821 0 : bool ignore_change{true};
822 : };
823 :
824 : /**
825 : * Filter and retrieve destinations stored in the addressbook
826 : */
827 : std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
828 :
829 : /**
830 : * Retrieve all the known labels in the address book
831 : */
832 : std::set<std::string> ListAddrBookLabels(const std::string& purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
833 :
834 : /**
835 : * Walk-through the address book entries.
836 : * Stops when the provided 'ListAddrBookFunc' returns false.
837 : */
838 : using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, const std::string& purpose, bool is_change)>;
839 : void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
840 :
841 : /**
842 : * Marks all outputs in each one of the destinations dirty, so their cache is
843 : * reset and does not return outdated information.
844 : */
845 : void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
846 :
847 : util::Result<CTxDestination> GetNewDestination(const std::string label);
848 : util::Result<CTxDestination> GetNewChangeDestination();
849 :
850 : isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
851 : isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
852 : /**
853 : * Returns amount of debit if the input matches the
854 : * filter, otherwise returns 0
855 : */
856 : CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
857 : isminetype IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
858 : bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
859 : isminetype IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
860 : /** should probably be renamed to IsRelevantToMe */
861 : bool IsFromMe(const CTransaction& tx) const;
862 : CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
863 : void chainStateFlushed(const CBlockLocator& loc) override;
864 :
865 : DBErrors LoadWallet();
866 : void AutoLockMasternodeCollaterals();
867 : DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
868 :
869 : bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
870 :
871 : bool DelAddressBook(const CTxDestination& address);
872 :
873 : bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
874 : bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
875 :
876 : std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
877 : bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
878 : bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
879 :
880 : unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
881 :
882 : //! signify that a particular wallet feature is now used.
883 : void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
884 :
885 : //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
886 4410 : int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
887 :
888 : //! Get wallet transactions that conflict with given transaction (spend same outputs)
889 : std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
890 :
891 : //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
892 : bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
893 :
894 : //! Flush wallet (bitdb flush)
895 : void Flush();
896 :
897 : //! Close wallet database
898 : void Close();
899 :
900 : /** Wallet is about to be unloaded */
901 : boost::signals2::signal<void ()> NotifyUnload;
902 :
903 : /**
904 : * Address book entry changed.
905 : * @note called without lock cs_wallet held.
906 : */
907 : boost::signals2::signal<void(const CTxDestination& address,
908 : const std::string& label, bool isMine,
909 : const std::string& purpose, ChangeType status)>
910 : NotifyAddressBookChanged;
911 :
912 : /**
913 : * Wallet transaction added, removed or updated.
914 : * @note called with lock cs_wallet held.
915 : */
916 : boost::signals2::signal<void(const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
917 :
918 : /** Show progress e.g. for rescan */
919 : boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
920 :
921 : /** Watch-only address added */
922 : boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
923 :
924 : /** Keypool has new keys */
925 : boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
926 :
927 : /** IS-lock received */
928 : boost::signals2::signal<void ()> NotifyISLockReceived;
929 :
930 : /** ChainLock received */
931 : boost::signals2::signal<void (int height)> NotifyChainLockReceived;
932 :
933 : /**
934 : * Wallet status (encrypted, locked) changed.
935 : * Note: Called without locks held.
936 : */
937 : boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
938 :
939 : /** Inquire whether this wallet broadcasts transactions. */
940 9890 : bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
941 : /** Set whether this wallet broadcasts transactions. */
942 2218 : void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
943 :
944 : /** Return whether transaction can be abandoned */
945 : bool TransactionCanBeAbandoned(const uint256& hashTx) const;
946 :
947 : /** Return whether transaction can be resent */
948 : bool TransactionCanBeResent(const uint256& hashTx) const;
949 :
950 : /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
951 : bool AbandonTransaction(const uint256& hashTx);
952 :
953 : /* Resend a transaction */
954 : bool ResendTransaction(const uint256& hashTx);
955 :
956 : /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
957 : static std::shared_ptr<CWallet> Create(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
958 :
959 : /**
960 : * Wallet post-init setup
961 : * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
962 : */
963 : void postInitProcess();
964 :
965 : /* AutoBackup functionality */
966 : static void InitAutoBackup();
967 : bool AutoBackupWallet(const fs::path& wallet_path, bilingual_str& error_string, std::vector<bilingual_str>& warnings);
968 :
969 : bool BackupWallet(const std::string& strDest) const;
970 :
971 : /**
972 : * HD Wallet Functions
973 : */
974 :
975 : /* Returns true if HD is enabled */
976 : bool IsHDEnabled() const;
977 :
978 : /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
979 : bool CanGetAddresses(bool internal = false) const;
980 :
981 : void notifyTransactionLock(const CTransactionRef &tx, const std::shared_ptr<const instantsend::InstantSendLock>& islock) override;
982 : void notifyChainLock(const CBlockIndex* pindexChainLock, const std::shared_ptr<const chainlock::ChainLockSig>& clsig) override;
983 :
984 : /** Load a CGovernanceObject into m_gobjects. */
985 : bool LoadGovernanceObject(const Governance::Object& obj) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
986 : /** Store a CGovernanceObject in the wallet database. This should only be used by governance objects that are created by this wallet via `gobject prepare`. */
987 : bool WriteGovernanceObject(const Governance::Object& obj) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
988 : /** Returns a vector containing pointers to the governance objects in m_gobjects */
989 : std::vector<const Governance::Object*> GetGovernanceObjects() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
990 :
991 : /**
992 : * Blocks until the wallet state is up-to-date to /at least/ the current
993 : * chain at the time this function is entered
994 : * Obviously holding cs_main/cs_wallet when going into this call may cause
995 : * deadlock
996 : */
997 : void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
998 :
999 : /** set a single wallet flag */
1000 : void SetWalletFlag(uint64_t flags);
1001 :
1002 : /** Unsets a single wallet flag */
1003 : void UnsetWalletFlag(uint64_t flag);
1004 :
1005 : /** check if a certain wallet flag is set */
1006 : bool IsWalletFlagSet(uint64_t flag) const override;
1007 :
1008 : /** overwrite all flags by the given uint64_t
1009 : flags must be uninitialised (or 0)
1010 : only known flags may be present */
1011 : void InitWalletFlags(uint64_t flags);
1012 : /** Loads the flags into the wallet. (used by LoadWallet) */
1013 : bool LoadWalletFlags(uint64_t flags);
1014 :
1015 : /** Determine if we are a legacy wallet */
1016 : bool IsLegacy() const;
1017 :
1018 : /** Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet has no name */
1019 368133 : std::string GetDisplayName() const override
1020 : {
1021 368133 : std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1022 368133 : return strprintf("[%s]", wallet_name);
1023 368133 : };
1024 :
1025 : /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
1026 : template<typename... Params>
1027 288072 : void WalletLogPrintf(std::string fmt, Params... parameters) const {
1028 288072 : LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1029 288072 : };
1030 :
1031 : /** Upgrade the wallet */
1032 : bool UpgradeWallet(int version, bilingual_str& error);
1033 :
1034 : //! Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers
1035 : std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1036 :
1037 : //! Returns all unique ScriptPubKeyMans
1038 : std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1039 :
1040 : //! Get the ScriptPubKeyMan for internal/external chain.
1041 : ScriptPubKeyMan* GetScriptPubKeyMan(bool internal) const;
1042 :
1043 : //! Get all the ScriptPubKeyMans for a script
1044 : std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
1045 : //! Get the ScriptPubKeyMan by id
1046 : ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1047 :
1048 : //! Get the SigningProvider for a script
1049 : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
1050 : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
1051 :
1052 : //! Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
1053 : LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1054 : LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1055 :
1056 : //! Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
1057 : void SetupLegacyScriptPubKeyMan();
1058 :
1059 : bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const override;
1060 :
1061 : bool HasEncryptionKeys() const override;
1062 :
1063 : /** Get last block processed height */
1064 4090533 : int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1065 : {
1066 4090533 : AssertLockHeld(cs_wallet);
1067 4090533 : assert(m_last_block_processed_height >= 0);
1068 4090533 : return m_last_block_processed_height;
1069 : };
1070 158498 : uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1071 : {
1072 158498 : AssertLockHeld(cs_wallet);
1073 158498 : assert(m_last_block_processed_height >= 0);
1074 158498 : return m_last_block_processed;
1075 : }
1076 : /** Set last block processed height, currently only use in unit test */
1077 2249 : void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1078 : {
1079 2249 : AssertLockHeld(cs_wallet);
1080 2249 : m_last_block_processed_height = block_height;
1081 2249 : m_last_block_processed = block_hash;
1082 2249 : };
1083 :
1084 : //! Connect the signals from ScriptPubKeyMans to the signals in CWallet
1085 : void ConnectScriptPubKeyManNotifiers();
1086 :
1087 : //! Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it
1088 : void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1089 :
1090 : //! Adds the active ScriptPubKeyMan for the specified type and internal. Writes it to the wallet file
1091 : //! @param[in] id The unique id for the ScriptPubKeyMan
1092 : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1093 : void AddActiveScriptPubKeyMan(uint256 id, bool internal);
1094 :
1095 : //! Loads an active ScriptPubKeyMan for the specified type and internal. (used by LoadWallet)
1096 : //! @param[in] id The unique id for the ScriptPubKeyMan
1097 : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1098 : void LoadActiveScriptPubKeyMan(uint256 id, bool internal);
1099 :
1100 : //! Remove specified ScriptPubKeyMan from set of active SPK managers. Writes the change to the wallet file.
1101 : //! @param[in] id The unique id for the ScriptPubKeyMan
1102 : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1103 : void DeactivateScriptPubKeyMan(uint256 id, bool internal);
1104 :
1105 : //! Create new DescriptorScriptPubKeyMans and add them to the wallet
1106 : void SetupDescriptorScriptPubKeyMans(const CExtKey& master_key, const SecureString& mnemonic, const SecureString mnemonic_passphrase) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1107 : void SetupDescriptorScriptPubKeyMans(const SecureString& mnemonic, const SecureString mnemonic_passphrase) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1108 :
1109 : //! Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet
1110 : DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1111 :
1112 : //! Returns whether the provided ScriptPubKeyMan is internal
1113 : //! @param[in] spk_man The ScriptPubKeyMan to test
1114 : //! @return contains value only for active DescriptorScriptPubKeyMan, otherwise undefined
1115 : std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1116 :
1117 : //! Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type
1118 : ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1119 :
1120 : /** Move all records from the BDB database to a new SQLite database for storage.
1121 : * The original BDB file will be deleted and replaced with a new SQLite file.
1122 : * A backup is not created.
1123 : * May crash if something unexpected happens in the filesystem.
1124 : */
1125 : bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1126 :
1127 : //! Get all of the descriptors from a legacy wallet
1128 : std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1129 :
1130 : //! Adds the ScriptPubKeyMans given in MigrationData to this wallet, removes LegacyScriptPubKeyMan,
1131 : //! and where needed, moves tx and address book entries to watchonly_wallet or solvable_wallet
1132 : bool ApplyMigrationData(MigrationData& data, bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1133 : };
1134 :
1135 : /**
1136 : * Called periodically by the schedule thread. Prompts individual wallets to resend
1137 : * their transactions. Actual rebroadcast schedule is managed by the wallets themselves.
1138 : */
1139 : void MaybeResendWalletTxs(WalletContext& context);
1140 :
1141 : /** RAII object to check and reserve a wallet rescan */
1142 : class WalletRescanReserver
1143 : {
1144 : private:
1145 : using Clock = std::chrono::steady_clock;
1146 : using NowFn = std::function<Clock::time_point()>;
1147 : CWallet& m_wallet;
1148 2076 : bool m_could_reserve{false};
1149 : NowFn m_now;
1150 : public:
1151 6228 : explicit WalletRescanReserver(CWallet& w) : m_wallet(w) {}
1152 :
1153 1980 : bool reserve()
1154 : {
1155 1980 : assert(!m_could_reserve);
1156 1980 : if (m_wallet.fScanningWallet.exchange(true)) {
1157 0 : return false;
1158 : }
1159 1980 : m_wallet.m_scanning_start = SteadyClock::now();
1160 1980 : m_wallet.m_scanning_progress = 0;
1161 1980 : m_wallet.fAbortRescan = false;
1162 1980 : m_could_reserve = true;
1163 1980 : return true;
1164 1980 : }
1165 :
1166 1498 : bool isReserved() const
1167 : {
1168 1498 : return (m_could_reserve && m_wallet.fScanningWallet);
1169 : }
1170 :
1171 143829 : Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
1172 :
1173 1 : void setNow(NowFn now) { m_now = std::move(now); }
1174 :
1175 4152 : ~WalletRescanReserver()
1176 2076 : {
1177 2076 : if (m_could_reserve) {
1178 1980 : m_wallet.fScanningWallet = false;
1179 1980 : }
1180 4152 : }
1181 :
1182 : };
1183 :
1184 : //! Add wallet name to persistent configuration so it will be loaded on startup.
1185 : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1186 :
1187 : //! Remove wallet name from persistent configuration so it will not be loaded on startup.
1188 : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1189 :
1190 : bool DummySignInput(const SigningProvider& provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl* coin_control = nullptr);
1191 :
1192 : bool FillInputToWeight(CTxIn& txin, int64_t target_weight);
1193 :
1194 : struct MigrationResult {
1195 : std::string wallet_name;
1196 : std::shared_ptr<CWallet> watchonly_wallet;
1197 : std::shared_ptr<CWallet> solvables_wallet;
1198 : fs::path backup_path;
1199 : };
1200 :
1201 : //! Do all steps to migrate a legacy wallet to a descriptor wallet
1202 : util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context);
1203 : } // namespace wallet
1204 :
1205 : #endif // BITCOIN_WALLET_WALLET_H
|