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