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 : : #ifndef BITCOIN_WALLET_WALLET_H
7 : : #define BITCOIN_WALLET_WALLET_H
8 : :
9 : : #include <addresstype.h>
10 : : #include <consensus/amount.h>
11 : : #include <interfaces/chain.h>
12 : : #include <interfaces/handler.h>
13 : : #include <kernel/cs_main.h>
14 : : #include <key.h>
15 : : #include <node/types.h>
16 : : #include <outputtype.h>
17 : : #include <policy/feerate.h>
18 : : #include <primitives/transaction.h>
19 : : #include <primitives/transaction_identifier.h>
20 : : #include <pubkey.h>
21 : : #include <script/interpreter.h>
22 : : #include <script/script.h>
23 : : #include <support/allocators/secure.h>
24 : : #include <sync.h>
25 : : #include <tinyformat.h>
26 : : #include <uint256.h>
27 : : #include <util/btcsignals.h>
28 : : #include <util/expected.h>
29 : : #include <util/fs.h>
30 : : #include <util/hasher.h>
31 : : #include <util/log.h>
32 : : #include <util/result.h>
33 : : #include <util/string.h>
34 : : #include <util/time.h>
35 : : #include <util/ui_change_type.h>
36 : : #include <wallet/crypter.h>
37 : : #include <wallet/db.h>
38 : : #include <wallet/scriptpubkeyman.h>
39 : : #include <wallet/transaction.h>
40 : : #include <wallet/types.h>
41 : : #include <wallet/walletutil.h>
42 : :
43 : : #include <atomic>
44 : : #include <cassert>
45 : : #include <cstddef>
46 : : #include <cstdint>
47 : : #include <functional>
48 : : #include <limits>
49 : : #include <map>
50 : : #include <memory>
51 : : #include <optional>
52 : : #include <set>
53 : : #include <string>
54 : : #include <unordered_map>
55 : : #include <utility>
56 : : #include <vector>
57 : :
58 : : class CKey;
59 : : class CKeyID;
60 : : class CPubKey;
61 : : class Coin;
62 : : class SigningProvider;
63 : : enum class MemPoolRemovalReason;
64 : : enum class SigningResult;
65 : : namespace common {
66 : : enum class PSBTError;
67 : : } // namespace common
68 : : namespace interfaces {
69 : : class Wallet;
70 : : }
71 : : namespace wallet {
72 : : class CWallet;
73 : : class WalletBatch;
74 : : enum class DBErrors : int;
75 : : } // namespace wallet
76 : : struct CBlockLocator;
77 : : struct CExtKey;
78 : : struct FlatSigningProvider;
79 : : struct KeyOriginInfo;
80 : : class PartiallySignedTransaction;
81 : : struct SignatureData;
82 : :
83 : : using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
84 : :
85 : : struct bilingual_str;
86 : :
87 : : namespace wallet {
88 : : class ChainScanner;
89 : : struct WalletContext;
90 : :
91 : : //! Explicitly delete the wallet.
92 : : //! Blocks the current thread until the wallet is destructed.
93 : : void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet);
94 : :
95 : : bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
96 : : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
97 : : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
98 : : std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
99 : : std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
100 : : std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
101 : : 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);
102 : : 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);
103 : : 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 = true, bool allow_unnamed = false);
104 : : std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
105 : : void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
106 : : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
107 : :
108 : : //! -fallbackfee default
109 : : inline constexpr CAmount DEFAULT_FALLBACK_FEE = 0;
110 : : //! -discardfee default
111 : : inline constexpr CAmount DEFAULT_DISCARD_FEE{10'000};
112 : : //! -mintxfee default
113 : : inline constexpr CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
114 : : //! -consolidatefeerate default
115 : : inline constexpr CAmount DEFAULT_CONSOLIDATE_FEERATE{10'000}; // 10 sat/vbyte
116 : : /**
117 : : * maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled by default
118 : : *
119 : : * A value of -1 disables this feature completely.
120 : : * A value of 0 (current default) means to attempt to do partial spend avoidance, and use its results if the fees remain *unchanged*
121 : : * 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].
122 : : */
123 : : inline constexpr CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE = 0;
124 : : //! discourage APS fee higher than this amount
125 : : inline constexpr CAmount HIGH_APS_FEE{COIN / 10000};
126 : : //! minimum recommended increment for replacement txs
127 : : inline constexpr CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
128 : : //! Default for -spendzeroconfchange
129 : : inline constexpr bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
130 : : //! Default for -walletrejectlongchains
131 : : inline constexpr bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
132 : : //! -txconfirmtarget default
133 : : inline constexpr unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
134 : : //! -walletrbf default
135 : : inline constexpr bool DEFAULT_WALLET_RBF = true;
136 : : inline constexpr bool DEFAULT_WALLETBROADCAST = true;
137 : : inline constexpr bool DEFAULT_DISABLE_WALLET = false;
138 : : inline constexpr bool DEFAULT_WALLETCROSSCHAIN = false;
139 : : //! -maxtxfee default
140 : : inline constexpr CAmount DEFAULT_TRANSACTION_MAXFEE{COIN / 10};
141 : : //! Discourage users to set fees higher than this amount (in satoshis) per kB
142 : : inline constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
143 : : //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
144 : : inline constexpr CAmount HIGH_MAX_TX_FEE{100 * HIGH_TX_FEE_PER_KB};
145 : : //! Pre-calculated constants for input size estimation in *virtual size*
146 : : inline constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
147 : :
148 : : class CCoinControl;
149 : :
150 : : //! Default for -addresstype
151 : : inline constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::BECH32};
152 : :
153 : : inline constexpr uint64_t KNOWN_WALLET_FLAGS =
154 : : WALLET_FLAG_AVOID_REUSE
155 : : | WALLET_FLAG_BLANK_WALLET
156 : : | WALLET_FLAG_KEY_ORIGIN_METADATA
157 : : | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
158 : : | WALLET_FLAG_DISABLE_PRIVATE_KEYS
159 : : | WALLET_FLAG_DESCRIPTORS
160 : : | WALLET_FLAG_EXTERNAL_SIGNER;
161 : :
162 : : inline constexpr uint64_t MUTABLE_WALLET_FLAGS =
163 : : WALLET_FLAG_AVOID_REUSE;
164 : :
165 : : static const std::map<WalletFlags, std::string> WALLET_FLAG_TO_STRING{
166 : : {WALLET_FLAG_AVOID_REUSE, "avoid_reuse"},
167 : : {WALLET_FLAG_BLANK_WALLET, "blank"},
168 : : {WALLET_FLAG_KEY_ORIGIN_METADATA, "key_origin_metadata"},
169 : : {WALLET_FLAG_LAST_HARDENED_XPUB_CACHED, "last_hardened_xpub_cached"},
170 : : {WALLET_FLAG_DISABLE_PRIVATE_KEYS, "disable_private_keys"},
171 : : {WALLET_FLAG_DESCRIPTORS, "descriptor_wallet"},
172 : : {WALLET_FLAG_EXTERNAL_SIGNER, "external_signer"}
173 : : };
174 : :
175 : : static const std::map<std::string, WalletFlags> STRING_TO_WALLET_FLAG{
176 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_AVOID_REUSE), WALLET_FLAG_AVOID_REUSE},
177 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_BLANK_WALLET), WALLET_FLAG_BLANK_WALLET},
178 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_KEY_ORIGIN_METADATA), WALLET_FLAG_KEY_ORIGIN_METADATA},
179 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED), WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
180 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_DISABLE_PRIVATE_KEYS), WALLET_FLAG_DISABLE_PRIVATE_KEYS},
181 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_DESCRIPTORS), WALLET_FLAG_DESCRIPTORS},
182 : : {WALLET_FLAG_TO_STRING.at(WALLET_FLAG_EXTERNAL_SIGNER), WALLET_FLAG_EXTERNAL_SIGNER}
183 : : };
184 : :
185 : : /** A wrapper to reserve an address from a wallet
186 : : *
187 : : * ReserveDestination is used to reserve an address.
188 : : * It is currently only used inside of CreateTransaction.
189 : : *
190 : : * Instantiating a ReserveDestination does not reserve an address. To do so,
191 : : * GetReservedDestination() needs to be called on the object. Once an address has been
192 : : * reserved, call KeepDestination() on the ReserveDestination object to make sure it is not
193 : : * returned. Call ReturnDestination() to return the address so it can be reused (for
194 : : * example, if the address was used in a new transaction
195 : : * and that transaction was not completed and needed to be aborted).
196 : : *
197 : : * If an address is reserved and KeepDestination() is not called, then the address will be
198 : : * returned when the ReserveDestination goes out of scope.
199 : : */
200 : : class ReserveDestination
201 : : {
202 : : protected:
203 : : //! The wallet to reserve from
204 : : const CWallet* const pwallet;
205 : : //! The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called
206 : : ScriptPubKeyMan* m_spk_man{nullptr};
207 : : OutputType const type;
208 : : //! The index of the address's key in the keypool
209 : : int64_t nIndex{-1};
210 : : //! The destination
211 : : CTxDestination address;
212 : : //! Whether this is from the internal (change output) keypool
213 : : bool fInternal{false};
214 : :
215 : : public:
216 : : //! Construct a ReserveDestination object. This does NOT reserve an address yet
217 : 4149 : explicit ReserveDestination(CWallet* pwallet, OutputType type)
218 : 4149 : : pwallet(pwallet)
219 [ + - ]: 4149 : , type(type) { }
220 : :
221 : : ReserveDestination(const ReserveDestination&) = delete;
222 : : ReserveDestination& operator=(const ReserveDestination&) = delete;
223 : :
224 : : //! Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool
225 : 4149 : ~ReserveDestination()
226 : : {
227 : 4149 : ReturnDestination();
228 [ + - ]: 4149 : }
229 : :
230 : : //! Reserve an address
231 : : util::Result<CTxDestination> GetReservedDestination(bool internal);
232 : : //! Return reserved address
233 : : void ReturnDestination();
234 : : //! Keep the address. Do not return its key to the keypool when this object goes out of scope
235 : : void KeepDestination();
236 : : };
237 : :
238 : : /**
239 : : * Address book data.
240 : : */
241 : 30676 : struct CAddressBookData
242 : : {
243 : : /**
244 : : * Address label which is always nullopt for change addresses. For sending
245 : : * and receiving addresses, it will be set to an arbitrary label string
246 : : * provided by the user, or to "", which is the default label. The presence
247 : : * or absence of a label is used to distinguish change addresses from
248 : : * non-change addresses by wallet transaction listing and fee bumping code.
249 : : */
250 : : std::optional<std::string> label;
251 : :
252 : : /**
253 : : * Address purpose which was originally recorded for payment protocol
254 : : * support but now serves as a cached IsMine value. Wallet code should
255 : : * not rely on this field being set.
256 : : */
257 : : std::optional<AddressPurpose> purpose;
258 : :
259 : : /**
260 : : * Whether coins with this address have previously been spent. Set when the
261 : : * the wallet avoid_reuse option is enabled and this is an IsMine address
262 : : * that has already received funds and spent them. This is used during coin
263 : : * selection to increase privacy by not creating different transactions
264 : : * that spend from the same addresses.
265 : : */
266 : : bool previously_spent{false};
267 : :
268 : : /**
269 : : * Map containing data about previously generated receive requests
270 : : * requesting funds to be sent to this address. Only present for IsMine
271 : : * addresses. Map keys are decimal numbers uniquely identifying each
272 : : * request, and map values are serialized RecentRequestEntry objects
273 : : * containing BIP21 URI information including message and amount.
274 : : */
275 : : std::map<std::string, std::string> receive_requests{};
276 : :
277 : : /** Accessor methods. */
278 [ + + - + ]: 12976 : bool IsChange() const { return !label.has_value(); }
[ + - # # ]
279 [ + - - + ]: 11967 : std::string GetLabel() const { return label ? *label : std::string{}; }
280 : 30657 : void SetLabel(std::string name) { label = std::move(name); }
281 : : };
282 : :
283 : 28297 : inline std::string PurposeToString(AddressPurpose p)
284 : : {
285 [ + + - - ]: 28297 : switch(p) {
286 : 28279 : case AddressPurpose::RECEIVE: return "receive";
287 : 18 : case AddressPurpose::SEND: return "send";
288 : 0 : case AddressPurpose::REFUND: return "refund";
289 : : } // no default case, so the compiler can warn about missing cases
290 : 0 : assert(false);
291 : : }
292 : :
293 : 2501 : inline std::optional<AddressPurpose> PurposeFromString(std::string_view s)
294 : : {
295 [ + + ]: 2501 : if (s == "receive") return AddressPurpose::RECEIVE;
296 [ + + ]: 42 : else if (s == "send") return AddressPurpose::SEND;
297 [ - + ]: 2 : else if (s == "refund") return AddressPurpose::REFUND;
298 : 2 : return {};
299 : : }
300 : :
301 [ + - + - : 90780 : struct CRecipient
+ - ][ - -
+ - + - +
- + - ]
[ # # ]
302 : : {
303 : : CTxDestination dest;
304 : : CAmount nAmount;
305 : : bool fSubtractFeeFromAmount;
306 : : };
307 : :
308 : :
309 : : /**
310 : : * A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.
311 : : */
312 : : class CWallet final : public WalletStorage, public interfaces::Chain::Notifications
313 : : {
314 : : private:
315 : : CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
316 : :
317 : : bool Unlock(const CKeyingMaterial& vMasterKeyIn);
318 : :
319 : : friend class ChainScanner;
320 : :
321 : : /** The next scheduled rebroadcast of wallet transactions. */
322 : : NodeClock::time_point m_next_resend{GetDefaultNextResend()};
323 : : /** Whether this wallet will submit newly created transactions to the node's mempool and
324 : : * prompt rebroadcasts (see ResendWalletTransactions()). */
325 : : bool fBroadcastTransactions = false;
326 : : // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
327 : : std::atomic<int64_t> m_best_block_time {0};
328 : :
329 : : // First created key time. Used to skip blocks prior to this time.
330 : : // 'std::numeric_limits<int64_t>::max()' if wallet is blank.
331 : : std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
332 : :
333 : : /**
334 : : * Used to keep track of spent outpoints, and
335 : : * detect and report conflicts (double-spends or
336 : : * mutated transactions where the mutant gets mined).
337 : : */
338 : : typedef std::unordered_multimap<COutPoint, Txid, SaltedOutpointHasher> TxSpends;
339 : : TxSpends mapTxSpends GUARDED_BY(cs_wallet);
340 : : void AddToSpends(const COutPoint& outpoint, const Txid& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
341 : : void AddToSpends(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
342 : :
343 : : /**
344 : : * Add a transaction to the wallet, or update it. confirm.block_* should
345 : : * be set when the transaction was known to be included in a block. When
346 : : * block_hash.IsNull(), then wallet state is not updated in AddToWallet, but
347 : : * notifications happen and cached balances are marked dirty.
348 : : *
349 : : * TODO: One exception to this is that the abandoned state is cleared under the
350 : : * assumption that any further notification of a transaction that was considered
351 : : * abandoned is an indication that it is not safe to be considered abandoned.
352 : : * Abandoned state should probably be more carefully tracked via different
353 : : * chain notifications or by checking mempool presence when necessary.
354 : : *
355 : : * Should be called with rescanning_old_block set to true, if the transaction is
356 : : * not discovered in real time, but during a rescan of old blocks.
357 : : */
358 : : bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
359 : :
360 : : /** Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
361 : : void MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx);
362 : :
363 : : enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
364 : :
365 : : using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
366 : :
367 : : /** Mark a transaction (and its in-wallet descendants) as a particular tx state. */
368 : : void RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
369 : : void RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
370 : :
371 : : /** Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
372 : : void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
373 : :
374 : : /** Collects all wallet txs that differ from wtx only in their scriptSigs (i.e. different tx id malleated variants)
375 : : * plus wtx itself. Sorted by the order in which they were inserted in the wallet (CWalletTx::nOrderPos) */
376 : : std::set<CWalletTx*, WalletTxOrderComparator> GetMalleatedVariants(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
377 : :
378 : : void SyncMalleatedTxMetadata(WalletBatch& batch, const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
379 : :
380 : : bool SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
381 : :
382 : : /** WalletFlags set on this wallet. */
383 : : std::atomic<uint64_t> m_wallet_flags{0};
384 : :
385 : : bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& strPurpose);
386 : :
387 : : //! Unsets a wallet flag and saves it to disk
388 : : void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
389 : :
390 : : //! Unset the blank wallet flag and saves it to disk
391 : : void UnsetBlankWalletFlag(WalletBatch& batch) override;
392 : :
393 : : /** Interface for accessing chain state. */
394 : : interfaces::Chain* m_chain;
395 : :
396 : : /** Wallet name: relative directory name or "" for default wallet. */
397 : : std::string m_name;
398 : :
399 : : /** Internal database handle. */
400 : : std::unique_ptr<WalletDatabase> m_database;
401 : :
402 : : std::unique_ptr<ChainScanner> m_scanner;
403 : :
404 : : /**
405 : : * The following is used to keep track of how far behind the wallet is
406 : : * from the chain sync, and to allow clients to block on us being caught up.
407 : : *
408 : : * Processed hash is a pointer on node's tip and doesn't imply that the wallet
409 : : * has scanned sequentially all blocks up to this one.
410 : : */
411 : : uint256 m_last_block_processed GUARDED_BY(cs_wallet);
412 : :
413 : : /** Height of last block processed is used by wallet to know depth of transactions
414 : : * without relying on Chain interface beyond asynchronous updates. For safety, we
415 : : * initialize it to -1. Height is a pointer on node's tip and doesn't imply
416 : : * that the wallet has scanned sequentially all blocks up to this one.
417 : : */
418 : : int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
419 : :
420 : : std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
421 : : std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
422 : :
423 : : // Indexed by a unique identifier produced by each ScriptPubKeyMan using
424 : : // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
425 : : std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
426 : :
427 : : // Appends spk managers into the main 'm_spk_managers'.
428 : : // Must be the only method adding data to it.
429 : : void AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man);
430 : :
431 : : // Same as 'AddActiveScriptPubKeyMan' but designed for use within a batch transaction context
432 : : void AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal);
433 : :
434 : : /** Store wallet flags */
435 : : void SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags);
436 : :
437 : : //! Cache of descriptor ScriptPubKeys used for IsMine. Maps ScriptPubKey to set of spkms
438 : : std::unordered_map<CScript, std::vector<ScriptPubKeyMan*>, SaltedSipHasher> m_cached_spks;
439 : :
440 : : //! Set of both spent and unspent transaction outputs owned by this wallet
441 : : std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher> m_txos GUARDED_BY(cs_wallet);
442 : :
443 : : /**
444 : : * Catch wallet up to current chain, scanning new blocks, updating the best
445 : : * block locator and m_last_block_processed, and registering for
446 : : * notifications about new blocks and transactions.
447 : : */
448 : : static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
449 : :
450 : : static NodeClock::time_point GetDefaultNextResend();
451 : :
452 : : // Update last block processed in memory only
453 : : void SetLastBlockProcessedInMem(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
454 : :
455 : : //! Update mempool conflicts for TRUC sibling transactions
456 : : void UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
457 : :
458 : : public:
459 : : /**
460 : : * Main wallet lock.
461 : : * This lock protects all the fields added by CWallet.
462 : : */
463 : : mutable RecursiveMutex cs_wallet;
464 : :
465 : 174512 : WalletDatabase& GetDatabase() const override
466 : : {
467 [ - + ]: 174512 : assert(static_cast<bool>(m_database));
468 : 174512 : return *m_database;
469 : : }
470 : :
471 : : /** Get a name for this wallet for logging/debugging purposes.
472 : : */
473 [ + - # # ]: 148525 : const std::string& GetName() const { return m_name; }
[ + - + - ]
[ - + - +
+ + + + -
- - - - -
+ - - + -
+ + + -
+ ][ + + +
- + - + -
+ - # # #
# # # # #
# # # # #
# ]
474 : :
475 : : typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
476 : : MasterKeyMap mapMasterKeys;
477 : : unsigned int nMasterKeyMaxID = 0;
478 : :
479 : : /** Construct wallet with specified name and database implementation. */
480 : : CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database);
481 : : ~CWallet();
482 : :
483 : : bool IsLocked() const override;
484 : : bool Lock();
485 : :
486 : : /** Interface to assert chain access */
487 [ - + + + ]: 10868 : bool HaveChain() const { return m_chain ? true : false; }
488 : :
489 : : /** Map from txid to CWalletTx for all transactions this wallet is
490 : : * interested in, including received and sent transactions. */
491 : : std::unordered_map<Txid, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
492 : :
493 : : typedef std::multimap<int64_t, CWalletTx*> TxItems;
494 : : TxItems wtxOrdered;
495 : :
496 : : int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
497 : :
498 : : std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
499 : : const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
500 : :
501 : : /** Set of Coins owned by this wallet that we won't try to spend from. A
502 : : * Coin may be locked if it has already been used to fund a transaction
503 : : * that hasn't confirmed yet. We wouldn't consider the Coin spent already,
504 : : * but also shouldn't try to use it again.
505 : : * bool to track whether this locked coin is persisted to disk.
506 : : */
507 : : std::map<COutPoint, bool> m_locked_coins GUARDED_BY(cs_wallet);
508 : :
509 : : /** Registered interfaces::Chain::Notifications handler. */
510 : : std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
511 : :
512 : : /** Interface for accessing chain state. */
513 [ - + ]: 902869 : interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
514 : :
515 : : const CWalletTx* GetWalletTx(const Txid& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
516 : :
517 : : std::set<Txid> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
518 : :
519 : 5349 : const std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher>& GetTXOs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return m_txos; };
520 : : std::optional<WalletTXO> GetTXO(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
521 : :
522 : : /** Cache outputs that belong to the wallet from a single transaction */
523 : : void RefreshTXOsFromTx(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
524 : : /** Cache outputs that belong to the wallet for all transactions in the wallet */
525 : : void RefreshAllTXOs() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
526 : :
527 : : /**
528 : : * Return depth of transaction in blockchain:
529 : : * <0 : conflicts with a transaction this deep in the blockchain
530 : : * 0 : in memory pool, waiting to be included in a block
531 : : * >=1 : this many blocks deep in the main chain
532 : : *
533 : : * Preconditions: it is only valid to call this function when the wallet is
534 : : * online and the block index is loaded. So this cannot be called by
535 : : * bitcoin-wallet tool code or by wallet migration code. If this is called
536 : : * without the wallet being online, it won't be able able to determine the
537 : : * the height of the last block processed, or the heights of blocks
538 : : * referenced in transaction, and might cause assert failures.
539 : : */
540 : : int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
541 : :
542 : : /**
543 : : * @return number of blocks to maturity for this transaction:
544 : : * 0 : is not a coinbase transaction, or is a mature coinbase transaction
545 : : * >0 : is a coinbase transaction which matures in this many blocks
546 : : */
547 : : int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
548 : : bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
549 : :
550 : : enum class SpendType {
551 : : UNSPENT,
552 : : CONFIRMED,
553 : : MEMPOOL,
554 : : NONMEMPOOL,
555 : : };
556 : : SpendType HowSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
557 : : bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
558 : :
559 : : // Whether this or any known scriptPubKey with the same single key has been spent.
560 : : bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
561 : : void SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
562 : :
563 : : /** Display address on an external signer. */
564 : : util::Result<void> DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
565 : :
566 : : bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
567 : : void LoadLockedCoin(const COutPoint& coin, bool persistent) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
568 : : bool LockCoin(const COutPoint& output, bool persist) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
569 : : bool UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
570 : : bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
571 : : void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
572 : :
573 : : ChainScanner& Scanner();
574 : : const ChainScanner& Scanner() const;
575 : :
576 : : //! Upgrade DescriptorCaches
577 : : void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
578 : :
579 : : //! Marks destination as previously spent.
580 : : void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
581 : : //! Appends payment request to destination.
582 : : void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
583 : :
584 : : //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
585 : : int64_t nRelockTime GUARDED_BY(cs_wallet){0};
586 : :
587 : : // Used to prevent concurrent calls to walletpassphrase RPC.
588 : : Mutex m_unlock_mutex;
589 : : // Used to prevent deleting the passphrase from memory when it is still in use.
590 : : RecursiveMutex m_relock_mutex;
591 : :
592 : : bool Unlock(const SecureString& strWalletPassphrase);
593 : : bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
594 : : bool EncryptWallet(const SecureString& strWalletPassphrase);
595 : :
596 : : unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
597 : :
598 : : /**
599 : : * Increment the next transaction order id
600 : : * @return next transaction order id
601 : : */
602 : : int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
603 : : DBErrors ReorderTransactions();
604 : :
605 : : void MarkDirty();
606 : :
607 : : //! Callback for updating transaction metadata in mapWallet.
608 : : //!
609 : : //! @param wtx - reference to mapWallet transaction to update
610 : : //! @param new_tx - true if wtx is newly inserted, false if it previously existed
611 : : //!
612 : : //! @return true if wtx is changed and needs to be saved to disk, otherwise false
613 : : using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
614 : :
615 : : /**
616 : : * Add the transaction to the wallet, wrapping it up inside a CWalletTx
617 : : * @return the recently added wtx pointer or nullptr if there was a db write error.
618 : : */
619 : : CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool rescanning_old_block = false);
620 : : bool LoadToWallet(CWalletTx&& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
621 : : void transactionAddedToMempool(const CTransactionRef& tx) override;
622 : : void blockConnected(const kernel::ChainstateRole& role, const interfaces::BlockInfo& block) override;
623 : : void blockDisconnected(const interfaces::BlockInfo& block) override;
624 : : void updatedBlockTip() override;
625 : : void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
626 : : /** Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average. */
627 [ + - ]: 22 : void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
628 : : /** Return true if all conditions for periodically resending transactions are met. */
629 : : bool ShouldResend() const;
630 : : void ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force);
631 : :
632 : : OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
633 : :
634 : : /** Fetch the inputs and sign with SIGHASH_ALL. */
635 : : bool SignTransaction(CMutableTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
636 : : /** Sign the tx given the input coins and sighash. */
637 : : bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
638 : : SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
639 : :
640 : : /**
641 : : * Fills out a PSBT with information from the wallet. Fills in UTXOs if we have
642 : : * them. Tries to sign if options.sign=true.
643 : : * Sets `complete` if the PSBT is now complete (i.e. has all required
644 : : * signatures or signature-parts, and is ready to finalize.)
645 : : *
646 : : * @param[in] psbtx PartiallySignedTransaction to fill in
647 : : * @param[in] options options for filling or signing
648 : : * @param[out] complete indicates whether the PSBT is now complete
649 : : * @param[out] n_signed the number of inputs signed by this wallet
650 : : * @returns an error if something goes wrong
651 : : */
652 : : std::optional<common::PSBTError> FillPSBT(PartiallySignedTransaction& psbtx,
653 : : const common::PSBTFillOptions& options,
654 : : bool& complete,
655 : : size_t* n_signed = nullptr) const;
656 : :
657 : : /**
658 : : * Submit the transaction to the node's mempool and then relay to peers.
659 : : * Should be called after CreateTransaction unless you want to abort
660 : : * broadcasting the transaction.
661 : : *
662 : : * @param[in] tx The transaction to be broadcast.
663 : : * @param[in] replaces_txid The txid of the transaction that this transaction replaces
664 : : * @param[in] comment The user's comment for this transaction
665 : : * @param[in] comment_to The comment for this transaction indicating where coins are sent to
666 : : * @param[in] messages The BIP 21 URI messages to attach to this transaction
667 : : */
668 : : void CommitTransaction(
669 : : CTransactionRef tx,
670 : : std::optional<Txid> replaces_txid = std::nullopt,
671 : 221 : std::optional<std::string> comment = std::nullopt,
672 [ + - ]: 442 : std::optional<std::string> comment_to = std::nullopt,
673 : : const std::vector<std::string>& messages = {},
674 : : const std::vector<std::string>& payment_requests = {}
675 : : );
676 : :
677 : : /** Pass this transaction to node for optional mempool insertion and relay to peers. */
678 : : bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, node::TxBroadcast broadcast_method) const
679 : : EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
680 : :
681 : : /** Updates wallet birth time if 'time' is below it */
682 : : void MaybeUpdateBirthTime(int64_t time);
683 : :
684 : : unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
685 : : /** Allow Coin Selection to pick unconfirmed UTXOs that were sent from our own wallet if it
686 : : * cannot fund the transaction otherwise. */
687 : : bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
688 : : bool m_signal_rbf{DEFAULT_WALLET_RBF};
689 : : bool m_allow_fallback_fee{true}; //!< will be false if -fallbackfee=0
690 : : CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE};
691 : : /**
692 : : * If fee estimation does not have enough data to provide estimates, use this fee instead.
693 : : * Has no effect if not using fee estimation
694 : : * Override with -fallbackfee
695 : : */
696 : : CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
697 : :
698 : : /** If the cost to spend a change output at this feerate is greater than the value of the
699 : : * output itself, just drop it to fees. */
700 : : CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
701 : :
702 : : /** When the actual feerate is less than the consolidate feerate, we will tend to make transactions which
703 : : * consolidate inputs. When the actual feerate is greater than the consolidate feerate, we will tend to make
704 : : * transactions which have the lowest fees.
705 : : */
706 : : CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
707 : :
708 : : /** The maximum fee amount we're willing to pay to prioritize partial spend avoidance. */
709 : : CAmount m_max_aps_fee{DEFAULT_MAX_AVOIDPARTIALSPEND_FEE}; //!< note: this is absolute fee, not fee rate
710 : : OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
711 : : /**
712 : : * Default output type for change outputs. When unset, automatically choose type
713 : : * based on address type setting and the types other of non-change outputs
714 : : * (see -changetype option documentation and implementation in
715 : : * CWallet::TransactionChangeType for details).
716 : : */
717 : : std::optional<OutputType> m_default_change_type{};
718 : : /** Absolute maximum transaction fee (in satoshis) used by default for the wallet */
719 : : CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
720 : :
721 : : /** Number of pre-generated keys/scripts by each spkm (part of the look-ahead process, used to detect payments) */
722 : : int64_t m_keypool_size{DEFAULT_KEYPOOL_SIZE};
723 : :
724 : : /** Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify) */
725 : : std::string m_notify_tx_changed_script;
726 : :
727 : : size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
728 : : bool TopUpKeyPool(unsigned int kpSize = 0);
729 : :
730 : : // Filter struct for 'ListAddrBookAddresses'
731 [ + - ]: 120 : struct AddrBookFilter {
732 : : // Fetch addresses with the provided label
733 : : std::optional<std::string> m_op_label{std::nullopt};
734 : : // Don't include change addresses by default
735 : : bool ignore_change{true};
736 : : };
737 : :
738 : : /**
739 : : * Filter and retrieve destinations stored in the addressbook
740 : : */
741 : : std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
742 : :
743 : : /**
744 : : * Retrieve all the known labels in the address book
745 : : */
746 : : std::set<std::string> ListAddrBookLabels(std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
747 : :
748 : : /**
749 : : * Walk-through the address book entries.
750 : : * Stops when the provided 'ListAddrBookFunc' returns false.
751 : : */
752 : : using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
753 : : void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
754 : :
755 : : /**
756 : : * Marks all outputs in each one of the destinations dirty, so their cache is
757 : : * reset and does not return outdated information.
758 : : */
759 : : void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
760 : :
761 : : util::Result<CTxDestination> GetNewDestination(OutputType type, const std::string& label);
762 : : util::Result<CTxDestination> GetNewChangeDestination(OutputType type);
763 : :
764 : : bool IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
765 : : bool IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
766 : : /** Returns amount of debit, i.e. the amount leaving this wallet due to this input */
767 : : CAmount GetDebit(const CTxIn& txin) const;
768 : : bool IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
769 : : bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
770 : : bool IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
771 : : /** should probably be renamed to IsRelevantToMe */
772 : : bool IsFromMe(const CTransaction& tx) const;
773 : : CAmount GetDebit(const CTransaction& tx) const;
774 : :
775 : : DBErrors PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings);
776 : :
777 : : /** Erases the provided transactions from the wallet. */
778 : : util::Result<void> RemoveTxs(std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
779 : : util::Result<void> RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
780 : :
781 : : bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
782 : :
783 : : bool DelAddressBook(const CTxDestination& address);
784 : : bool DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address);
785 : :
786 : : bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
787 : : bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
788 : :
789 : : std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
790 : : bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
791 : : bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
792 : :
793 : : unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
794 : :
795 : : //! Get wallet transactions that conflict with given transaction (spend same outputs)
796 : : std::set<Txid> GetConflicts(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
797 : :
798 : : //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
799 : : bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
800 : :
801 : : //! Close wallet database
802 : : void Close();
803 : :
804 : : /** Wallet is about to be unloaded */
805 : : btcsignals::signal<void ()> NotifyUnload;
806 : :
807 : : /**
808 : : * Address book entry changed.
809 : : * @note called without lock cs_wallet held.
810 : : */
811 : : btcsignals::signal<void(const CTxDestination& address,
812 : : const std::string& label, bool isMine,
813 : : AddressPurpose purpose, ChangeType status)>
814 : : NotifyAddressBookChanged;
815 : :
816 : : /**
817 : : * Wallet transaction added, removed or updated.
818 : : * @note called with lock cs_wallet held.
819 : : */
820 : : btcsignals::signal<void(const Txid& hashTx, ChangeType status)> NotifyTransactionChanged;
821 : :
822 : : /** Show progress e.g. for rescan */
823 : : btcsignals::signal<void (const std::string &title, int nProgress)> ShowProgress;
824 : :
825 : : /** Keypool has new keys */
826 : : btcsignals::signal<void ()> NotifyCanGetAddressesChanged;
827 : :
828 : : /**
829 : : * Wallet status (encrypted, locked) changed.
830 : : * Note: Called without locks held.
831 : : */
832 : : btcsignals::signal<void (CWallet* wallet)> NotifyStatusChanged;
833 : :
834 : : /** Inquire whether this wallet broadcasts transactions. */
835 [ + - ]: 1818 : bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
836 : : /** Set whether this wallet broadcasts transactions. */
837 : 1088 : void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
838 : :
839 : : /** Return whether transaction can be abandoned */
840 : : bool TransactionCanBeAbandoned(const Txid& hashTx) const;
841 : :
842 : : /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
843 : : bool AbandonTransaction(const Txid& hashTx);
844 : : bool AbandonTransaction(CWalletTx& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
845 : :
846 : : /** Mark a transaction as replaced by another transaction. */
847 : : bool MarkReplaced(const Txid& originalHash, const Txid& newHash);
848 : :
849 : : static bool LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings);
850 : :
851 : : /* Initializes, creates and returns a new CWallet; returns a null pointer in case of an error */
852 : : static std::shared_ptr<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);
853 : :
854 : : /* Initializes, loads, and returns a CWallet from an existing wallet; returns a null pointer in case of an error */
855 : : static std::shared_ptr<CWallet> LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings);
856 : :
857 : : /**
858 : : * Wallet post-init setup
859 : : * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
860 : : */
861 : : void postInitProcess();
862 : :
863 : : [[nodiscard]] bool BackupWallet(const std::string& strDest) const;
864 : :
865 : : /* Returns true if HD is enabled */
866 : : bool IsHDEnabled() const;
867 : :
868 : : /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
869 : : bool CanGetAddresses(bool internal = false) const;
870 : :
871 : : /* Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction */
872 [ + + ]: 446 : int64_t GetBirthTime() const { return m_birth_time; }
873 : :
874 : : /**
875 : : * Blocks until the wallet state is up-to-date to /at least/ the current
876 : : * chain at the time this function is entered
877 : : * Obviously holding cs_main/cs_wallet when going into this call may cause
878 : : * deadlock
879 : : */
880 : : void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
881 : :
882 : : /** set a single wallet flag */
883 : : void SetWalletFlag(uint64_t flags);
884 : :
885 : : /** Unsets a single wallet flag */
886 : : void UnsetWalletFlag(uint64_t flag);
887 : :
888 : : /** check if a certain wallet flag is set */
889 : : bool IsWalletFlagSet(uint64_t flag) const override;
890 : :
891 : : /** overwrite all flags by the given uint64_t
892 : : flags must be uninitialised (or 0)
893 : : only known flags may be present */
894 : : void InitWalletFlags(uint64_t flags);
895 : : /** Loads the flags into the wallet. (used by LoadWallet) */
896 : : bool LoadWalletFlags(uint64_t flags);
897 : : //! Retrieve all of the wallet's flags
898 : : uint64_t GetWalletFlags() const;
899 : :
900 : : /** Return wallet name for use in logs, will return "default wallet" if the wallet has no name. */
901 : 57947 : std::string LogName() const override
902 : : {
903 [ - + ]: 57947 : std::string name{GetName()};
904 [ + + + - ]: 114307 : return name.empty() ? "default wallet" : name;
905 : 57947 : };
906 : :
907 : : /** Return wallet name for display, like LogName() but translates "default wallet" string. */
908 : 2369 : std::string DisplayName() const
909 : : {
910 [ - + ]: 2369 : std::string name{GetName()};
911 [ + + + - ]: 4673 : return name.empty() ? _("default wallet") : name;
912 : 2369 : };
913 : :
914 : : /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
915 : : template <typename... Params>
916 : 57437 : void WalletLogPrintf(util::ConstevalFormatString<sizeof...(Params)> wallet_fmt, const Params&... params) const
917 : : {
918 [ + - + - ]: 57437 : LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
919 : 57437 : };
920 : :
921 : 1039 : void LogStats() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
922 : : {
923 : 1039 : AssertLockHeld(cs_wallet);
924 : 1039 : WalletLogPrintf("setKeyPool.size() = %u\n", GetKeyPoolSize());
925 : 1039 : WalletLogPrintf("mapWallet.size() = %u\n", mapWallet.size());
926 : 1039 : WalletLogPrintf("m_address_book.size() = %u\n", m_address_book.size());
927 : 1039 : };
928 : :
929 : : //! Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers
930 : : std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
931 : : bool IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const;
932 : :
933 : : //! Returns all unique ScriptPubKeyMans
934 : : std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
935 : :
936 : : //! Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
937 : : ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
938 : :
939 : : //! Get all the ScriptPubKeyMans for a script
940 : : std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
941 : : //! Get the ScriptPubKeyMan by id
942 : : ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
943 : :
944 : : //! Get the SigningProvider for a script
945 : : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
946 : : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
947 : :
948 : : //! Get the wallet descriptors for a script.
949 : : std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
950 : :
951 : : //! Get the LegacyDataSPKM used for all legacy output types and both internal and external chains.
952 : : LegacyDataSPKM* GetLegacyDataSPKM() const;
953 : : LegacyDataSPKM* GetOrCreateLegacyDataSPKM();
954 : :
955 : : //! Create a LegacyDataSPKM and set it for all legacy output types and both internal and external chains.
956 : : void SetupLegacyDataSPKM();
957 : :
958 : : bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const override;
959 : :
960 : : bool HasEncryptionKeys() const override;
961 : : bool HaveCryptedKeys() const;
962 : :
963 : : /** Get last block processed height */
964 : 1239696 : int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
965 : : {
966 : 1239696 : AssertLockHeld(cs_wallet);
967 [ - + ]: 1239696 : assert(m_last_block_processed_height >= 0);
968 : 1239696 : return m_last_block_processed_height;
969 : : };
970 : 86780 : uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
971 : : {
972 : 86780 : AssertLockHeld(cs_wallet);
973 [ - + ]: 86780 : assert(m_last_block_processed_height >= 0);
974 : 86780 : return m_last_block_processed;
975 : : }
976 : : /** Set last block processed height, and write to database */
977 : : void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
978 : : /** Write the current best block to database */
979 : : void WriteBestBlock() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
980 : :
981 : : //! Connect the signals from ScriptPubKeyMans to the signals in CWallet
982 : : void ConnectScriptPubKeyManNotifiers();
983 : :
984 : : //! Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it
985 : : void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc, const KeyMap& keys, const CryptedKeyMap& ckeys);
986 : :
987 : : //! Adds the active ScriptPubKeyMan for the specified type and internal. Writes it to the wallet file
988 : : //! @param[in] id The unique id for the ScriptPubKeyMan
989 : : //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
990 : : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
991 : : void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
992 : :
993 : : //! Loads an active ScriptPubKeyMan for the specified type and internal. (used by LoadWallet)
994 : : //! @param[in] id The unique id for the ScriptPubKeyMan
995 : : //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
996 : : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
997 : : void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
998 : :
999 : : //! Remove specified ScriptPubKeyMan from set of active SPK managers. Writes the change to the wallet file.
1000 : : //! @param[in] id The unique id for the ScriptPubKeyMan
1001 : : //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1002 : : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1003 : : void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1004 : :
1005 : : //! Create new DescriptorScriptPubKeyMan and add it to the wallet
1006 : : DescriptorScriptPubKeyMan& SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1007 : : //! Create new DescriptorScriptPubKeyMans and add them to the wallet
1008 : : void SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1009 : : void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1010 : :
1011 : : //! Create new seed and default DescriptorScriptPubKeyMans for this wallet
1012 : : void SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1013 : :
1014 : : //! Setup new descriptors or seed for new address generation
1015 : : void SetupWalletGeneration() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1016 : :
1017 : : //! Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet
1018 : : DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1019 : :
1020 : : //! Returns whether the provided ScriptPubKeyMan is internal
1021 : : //! @param[in] spk_man The ScriptPubKeyMan to test
1022 : : //! @return contains value only for active DescriptorScriptPubKeyMan, otherwise undefined
1023 : : std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1024 : :
1025 : : //! Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type
1026 : : util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1027 : :
1028 : : //! Add an HD key to the wallet and return its master xpub.
1029 : : //! Requires the wallet to be unlocked. Returns a `WalletError` with code
1030 : : //! `WalletErrorCode::UnlockNeeded` if the wallet is locked.
1031 : : //!
1032 : : //! @param[in] key Optional extended private key to add. If not provided,
1033 : : //! a new random HD key will be generated.
1034 : : //! @return The master xpub for the added HD key, or a `WalletError` on failure.
1035 : : util::Expected<CExtPubKey, WalletError> AddHDKey(const std::optional<CExtKey>& key);
1036 : :
1037 : : /** Move all records from the BDB database to a new SQLite database for storage.
1038 : : * The original BDB file will be deleted and replaced with a new SQLite file.
1039 : : * A backup is not created.
1040 : : * May crash if something unexpected happens in the filesystem.
1041 : : */
1042 : : bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1043 : :
1044 : : //! Get all of the descriptors from a legacy wallet
1045 : : std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1046 : :
1047 : : //! Adds the ScriptPubKeyMans from MigrationData to this wallet, removes the LegacyDataSPKM,
1048 : : //! and moves transaction and address book entries to watchonly_wallet or solvable_wallet as needed.
1049 : : util::Result<void> ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1050 : :
1051 : : //! Whether the (external) signer performs R-value signature grinding
1052 : : bool CanGrindR() const;
1053 : :
1054 : : //! Add scriptPubKeys for this ScriptPubKeyMan into the scriptPubKey cache
1055 : : void CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm);
1056 : :
1057 : : void TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm) override;
1058 : :
1059 : : //! Which descriptors GetHDPubKeys() should consider.
1060 : : enum class HDKeyFilter {
1061 : : Active, //!< Only active descriptors
1062 : : All, //!< All descriptors
1063 : : UnusedKey, //!< Only unused(KEY) descriptors
1064 : : };
1065 : : using HDPubKeyMap = std::map<CExtPubKey, std::set<DescriptorScriptPubKeyMan*>>;
1066 : : //! Retrieve descriptor xpubs matching the requested filter.
1067 : : HDPubKeyMap GetHDPubKeys(HDKeyFilter filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1068 : :
1069 : : //! Find the private key for the given key id from the wallet's descriptors, if available
1070 : : //! Returns nullopt when no descriptor has the key or if the wallet is locked.
1071 : : std::optional<CKey> GetKey(const CKeyID& keyid) const;
1072 : :
1073 : : //! Reconstruct the extended private key for an HD xpub. Returns nullopt when
1074 : : //! no descriptor has the private key, or the wallet is locked.
1075 : : std::optional<CExtKey> GetExtKey(const CExtPubKey& xpub) const;
1076 : :
1077 : : //! Disconnect chain notifications and wait for all notifications to be processed
1078 : : void DisconnectChainNotifications();
1079 : : };
1080 : :
1081 : : /**
1082 : : * Called periodically by the schedule thread. Prompts individual wallets to resend
1083 : : * their transactions. Actual rebroadcast schedule is managed by the wallets themselves.
1084 : : */
1085 : : void MaybeResendWalletTxs(WalletContext& context);
1086 : :
1087 : :
1088 : : //! Add wallet name to persistent configuration so it will be loaded on startup.
1089 : : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1090 : :
1091 : : //! Remove wallet name from persistent configuration so it will not be loaded on startup.
1092 : : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1093 : :
1094 : : struct MigrationResult {
1095 : : std::string wallet_name;
1096 : : std::optional<std::string> watchonly_wallet_name;
1097 : : std::optional<std::string> solvables_wallet_name;
1098 : : std::shared_ptr<CWallet> wallet;
1099 : : std::shared_ptr<CWallet> watchonly_wallet;
1100 : : std::shared_ptr<CWallet> solvables_wallet;
1101 : : fs::path backup_path;
1102 : : };
1103 : :
1104 : : //! Do all steps to migrate a legacy wallet to a descriptor wallet
1105 : : [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context, bool load_wallet = true);
1106 : : //! Requirement: The wallet provided to this function must be isolated, with no attachment to the node's context.
1107 : : [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context, bool load_wallet = true);
1108 : :
1109 : : //! Determine the path that the wallet is stored in
1110 : : util::Result<fs::path> GetWalletPath(const std::string& name);
1111 : : } // namespace wallet
1112 : :
1113 : : #endif // BITCOIN_WALLET_WALLET_H
|