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