LCOV - code coverage report
Current view: top level - src/wallet - wallet.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 58.6 % 133 78
Test Date: 2024-07-04 04:02:30 Functions: 34.7 % 75 26
Branches: 12.9 % 622 80

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

Generated by: LCOV version 2.0-1