LCOV - code coverage report
Current view: top level - src/wallet - wallet.h (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 164 185 88.6 %
Date: 2025-02-23 09:33:43 Functions: 13 19 68.4 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2021 The Bitcoin developers
       3             : // Copyright (c) 2014-2015 The Dash developers
       4             : // Copyright (c) 2015-2022 The PIVX Core developers
       5             : // Distributed under the MIT software license, see the accompanying
       6             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       7             : 
       8             : #ifndef PIVX_WALLET_WALLET_H
       9             : #define PIVX_WALLET_WALLET_H
      10             : 
      11             : #include "addressbook.h"
      12             : #include "amount.h"
      13             : #include "consensus/tx_verify.h"
      14             : #include "consensus/validation.h"
      15             : #include "crypter.h"
      16             : #include "destination_io.h"
      17             : #include "kernel.h"
      18             : #include "key.h"
      19             : #include "key_io.h"
      20             : #include "keystore.h"
      21             : #include "operationresult.h"
      22             : #include "policy/feerate.h"
      23             : #include "primitives/block.h"
      24             : #include "primitives/transaction.h"
      25             : #include "sapling/address.h"
      26             : #include "guiinterface.h"
      27             : #include "util/system.h"
      28             : #include "utilstrencodings.h"
      29             : #include "validationinterface.h"
      30             : #include "script/ismine.h"
      31             : #include "wallet/scriptpubkeyman.h"
      32             : #include "sapling/saplingscriptpubkeyman.h"
      33             : #include "validation.h"
      34             : #include "wallet/walletdb.h"
      35             : 
      36             : #include <algorithm>
      37             : #include <atomic>
      38             : #include <map>
      39             : #include <set>
      40             : #include <stdexcept>
      41             : #include <stdint.h>
      42             : #include <string>
      43             : #include <utility>
      44             : #include <vector>
      45             : 
      46             : typedef CWallet* CWalletRef;
      47             : extern std::vector<CWalletRef> vpwallets;
      48             : 
      49             : /**
      50             :  * Settings
      51             :  */
      52             : extern CFeeRate payTxFee;
      53             : extern CAmount maxTxFee;
      54             : extern unsigned int nTxConfirmTarget;
      55             : extern bool bSpendZeroConfChange;
      56             : extern bool bdisableSystemnotifications;
      57             : extern bool fPayAtLeastCustomFee;
      58             : 
      59             : //! -paytxfee default
      60             : static const CAmount DEFAULT_TRANSACTION_FEE = 0;
      61             : //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
      62             : static const CAmount nHighTransactionFeeWarning = 0.1 * COIN;
      63             : //! -mintxfee default
      64             : static const CAmount DEFAULT_TRANSACTION_MINFEE = 10000;
      65             : //! -maxtxfee default
      66             : static const CAmount DEFAULT_TRANSACTION_MAXFEE = 1 * COIN;
      67             : //! minimum change amount
      68             : static const CAmount MIN_CHANGE = CENT;
      69             : //! -txconfirmtarget default
      70             : static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 1;
      71             : //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
      72             : static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
      73             : //! -minstakesplit default
      74             : static const CAmount DEFAULT_MIN_STAKE_SPLIT_THRESHOLD = 100 * COIN;
      75             : //! Default for -spendzeroconfchange
      76             : static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
      77             : //! Default for -staking
      78             : static const bool DEFAULT_STAKING = true;
      79             : //! Default for -coldstaking
      80             : static const bool DEFAULT_COLDSTAKING = true;
      81             : //! Defaults for -gen and -genproclimit
      82             : static const bool DEFAULT_GENERATE = false;
      83             : static const unsigned int DEFAULT_GENERATE_PROCLIMIT = 1;
      84             : //! Default for -createwalletbackups
      85             : static const unsigned int DEFAULT_CREATEWALLETBACKUPS = 10;
      86             : //! Default for -disablewallet
      87             : static const bool DEFAULT_DISABLE_WALLET = false;
      88             : 
      89             : static const int64_t TIMESTAMP_MIN = 0;
      90             : 
      91             : class CAddressBookIterator;
      92             : class CCoinControl;
      93             : class COutput;
      94             : class CStakeableOutput;
      95             : class CReserveKey;
      96             : class CScript;
      97             : class CScheduler;
      98             : class ScriptPubKeyMan;
      99             : class SaplingScriptPubKeyMan;
     100             : class SaplingNoteData;
     101             : struct SaplingNoteEntry;
     102             : 
     103             : /** (client) version numbers for particular wallet features */
     104             : enum WalletFeature {
     105             :     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
     106             : 
     107             :     FEATURE_WALLETCRYPT = 40000, // wallet encryption
     108             :     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
     109             : 
     110             :     FEATURE_PRE_PIVX = 61000, // inherited version..
     111             : 
     112             :     // The following features were implemented in BTC but not in our wallet, we can simply skip them.
     113             :     // FEATURE_HD = 130000,  Hierarchical key derivation after BIP32 (HD Wallet)
     114             :     // FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
     115             : 
     116             :     FEATURE_PRE_SPLIT_KEYPOOL = 169900, // Upgraded to HD SPLIT and can have a pre-split keypool
     117             : 
     118             :     FEATURE_SAPLING = 170000, // Upgraded to Saplings key manager.
     119             : 
     120             :     FEATURE_LATEST = FEATURE_SAPLING
     121             : };
     122             : 
     123             : /** A key pool entry */
     124             : class CKeyPool
     125             : {
     126             : public:
     127             :     //! The time at which the key was generated. Set in AddKeypoolPubKeyWithDB
     128             :     int64_t nTime;
     129             :     //! The public key
     130             :     CPubKey vchPubKey;
     131             :     //! Whether this keypool entry is in the internal, external or staking keypool.
     132             :     uint8_t type;
     133             :     //! Whether this key was generated for a keypool before the wallet was upgraded to HD-split
     134             :     bool m_pre_split;
     135             : 
     136             :     CKeyPool();
     137             :     CKeyPool(const CPubKey& vchPubKeyIn, const uint8_t& type);
     138             : 
     139        8492 :     bool IsInternal() const { return type == HDChain::ChangeType::INTERNAL; }
     140        1386 :     bool IsExternal() const { return type == HDChain::ChangeType::EXTERNAL; }
     141        7118 :     bool IsStaking() const { return type == HDChain::ChangeType::STAKING; }
     142             : 
     143             :     template<typename Stream>
     144       11507 :     void Serialize(Stream& s) const
     145             :     {
     146       11507 :         int nVersion = s.GetVersion();
     147       11507 :         if (!(s.GetType() & SER_GETHASH)) {
     148       11507 :             s << nVersion;
     149             :         }
     150       11507 :         s << nTime << vchPubKey << Span<unsigned char>((unsigned char*)&type, 1) << m_pre_split;
     151       11507 :     }
     152             : 
     153             :     template<typename Stream>
     154        9107 :     void Unserialize(Stream& s)
     155             :     {
     156        9107 :         int nVersion = s.GetVersion();
     157        9107 :         if (!(s.GetType() & SER_GETHASH)) {
     158        9107 :             s >> nVersion;
     159             :         }
     160        9107 :         s >> nTime >> vchPubKey;
     161             :         try {
     162        9107 :             s >> Span<unsigned char>((unsigned char*)&type, 1);
     163         300 :         } catch (std::ios_base::failure&) {
     164             :             /* flag as external address if we can't read the internal boolean
     165             :                (this will be the case for any wallet before the HD chain split version) */
     166         300 :             type = HDChain::ChangeType::EXTERNAL;
     167             :         }
     168             :         try {
     169        9107 :             s >> m_pre_split;
     170         300 :         } catch (std::ios_base::failure&) {
     171             :             /* flag as pre-split address if we can't read the m_pre_split boolean
     172             :                (this will be the case for any wallet prior to the HD chain upgrade) */
     173         300 :             m_pre_split = true;
     174             :         }
     175        9107 :     }
     176             : };
     177             : 
     178             : /** Record info about last stake attempt:
     179             :  *  - tipBlock       index of the block on top of which last stake attempt was made
     180             :  *  - nTime          time slot of last attempt
     181             :  *  - nTries         number of UTXOs hashed during last attempt
     182             :  *  - nCoins         number of stakeable utxos during last attempt
     183             : **/
     184         505 : class CStakerStatus
     185             : {
     186             : private:
     187             :     const CBlockIndex* tipBlock{nullptr};
     188             :     int64_t nTime{0};
     189             :     int nTries{0};
     190             :     int nCoins{0};
     191             : 
     192             : public:
     193             :     // Get
     194        2214 :     const CBlockIndex* GetLastTip() const { return tipBlock; }
     195         561 :     uint256 GetLastHash() const { return (GetLastTip() == nullptr ? UINT256_ZERO : GetLastTip()->GetBlockHash()); }
     196         561 :     int GetLastHeight() const { return (GetLastTip() == nullptr ? 0 : GetLastTip()->nHeight); }
     197         561 :     int GetLastCoins() const { return nCoins; }
     198         561 :     int GetLastTries() const { return nTries; }
     199         561 :     int64_t GetLastTime() const { return nTime; }
     200             :     // Set
     201        1925 :     void SetLastCoins(const int coins) { nCoins = coins; }
     202       12726 :     void SetLastTries(const int tries) { nTries = tries; }
     203        1925 :     void SetLastTip(const CBlockIndex* lastTip) { tipBlock = lastTip; }
     204       12726 :     void SetLastTime(const uint64_t lastTime) { nTime = lastTime; }
     205           0 :     void SetNull()
     206             :     {
     207           0 :         SetLastCoins(0);
     208           0 :         SetLastTries(0);
     209           0 :         SetLastTip(nullptr);
     210           0 :         SetLastTime(0);
     211           0 :     }
     212             :     // Check whether staking status is active (last attempt earlier than 30 seconds ago)
     213         562 :     bool IsActive() const { return (nTime + 30) >= GetTime(); }
     214             : };
     215             : 
     216         332 : class CRecipientBase {
     217             : public:
     218             :     CAmount nAmount;
     219             :     bool fSubtractFeeFromAmount;
     220        1692 :     CRecipientBase(const CAmount& _nAmount, bool _fSubtractFeeFromAmount) :
     221        1347 :                    nAmount(_nAmount), fSubtractFeeFromAmount(_fSubtractFeeFromAmount) {}
     222           0 :     virtual bool isTransparent() const { return true; };
     223           0 :     virtual Optional<CScript> getScript() const { return nullopt; }
     224           0 :     virtual Optional<libzcash::SaplingPaymentAddress> getSapPaymentAddr() const { return nullopt; }
     225           0 :     virtual std::string getMemo() const { return ""; }
     226             : };
     227             : 
     228        1273 : class CRecipient final : public CRecipientBase
     229             : {
     230             : public:
     231             :     CScript scriptPubKey;
     232         556 :     CRecipient(const CScript& _scriptPubKey, const CAmount& _nAmount, bool _fSubtractFeeFromAmount) :
     233         556 :             CRecipientBase(_nAmount, _fSubtractFeeFromAmount), scriptPubKey(_scriptPubKey) {}
     234         137 :     bool isTransparent() const override { return true; }
     235          38 :     Optional<CScript> getScript() const override { return {scriptPubKey}; }
     236             : };
     237             : 
     238             : class CAddressBookIterator
     239             : {
     240             : public:
     241         146 :     explicit CAddressBookIterator(std::map<CWDestination, AddressBook::CAddressBookData>& _map) : map(_map), it(_map.begin()), itEnd(_map.end()) {}
     242             :     const CWDestination* GetDestKey();
     243             :     const CTxDestination* GetCTxDestKey();
     244             :     const libzcash::SaplingPaymentAddress* GetShieldedDestKey();
     245        1427 :     AddressBook::CAddressBookData GetValue() { return it->second; }
     246             : 
     247        1573 :     bool IsValid() { return it != itEnd; }
     248             : 
     249        1427 :     bool Next() {
     250        1427 :         if (!IsValid()) return false;
     251        1427 :         it++;
     252        1427 :         return IsValid();
     253             :     }
     254             : 
     255          67 :     void SetFilter(CTxDestination& filter)
     256             :     {
     257          67 :         it = map.find(filter);
     258          67 :         if (it != itEnd) {
     259          65 :             itEnd = std::next(it);
     260             :         }
     261          67 :     }
     262             : 
     263             : private:
     264             :     std::map<CWDestination, AddressBook::CAddressBookData>& map;
     265             :     std::map<CWDestination, AddressBook::CAddressBookData>::iterator it;
     266             :     std::map<CWDestination, AddressBook::CAddressBookData>::iterator itEnd;
     267             : };
     268             : 
     269             : template <class T>
     270             : using TxSpendMap = std::multimap<T, uint256>;
     271             : typedef std::map<SaplingOutPoint, SaplingNoteData> mapSaplingNoteData_t;
     272             : 
     273             : typedef std::map<std::string, std::string> mapValue_t;
     274             : 
     275        6763 : static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
     276             : {
     277       13526 :     if (!mapValue.count("n")) {
     278           0 :         nOrderPos = -1; // TODO: calculate elsewhere
     279           0 :         return;
     280             :     }
     281        6763 :     nOrderPos = atoi64(mapValue["n"].c_str());
     282             : }
     283             : 
     284             : 
     285      336572 : static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
     286             : {
     287      336572 :     if (nOrderPos == -1)
     288             :         return;
     289      336571 :     mapValue["n"] = i64tostr(nOrderPos);
     290             : }
     291             : 
     292        1220 : struct COutputEntry {
     293             :     CTxDestination destination;
     294             :     CAmount amount;
     295             :     int vout;
     296             : };
     297             : 
     298             : /** Legacy class used for deserializing vtxPrev for backwards compatibility.
     299             :  * vtxPrev was removed in commit 93a18a3650292afbb441a47d1fa1b94aeb0164e3,
     300             :  * but old wallet.dat files may still contain vtxPrev vectors of CMerkleTxs.
     301             :  * These need to get deserialized for field alignment when deserializing
     302             :  * a CWalletTx, but the deserialized values are discarded.**/
     303             : class CMerkleTx
     304             : {
     305             : private:
     306             : 
     307             : public:
     308             :     template<typename Stream>
     309           0 :     void Unserialize(Stream& s)
     310             :     {
     311           0 :         CTransactionRef tx;
     312           0 :         uint256 hashBlock;
     313           0 :         std::vector<uint256> vMerkleBranch;
     314             :         int nIndex;
     315             : 
     316           0 :         s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
     317           0 :     }
     318             : };
     319             : 
     320             : /**
     321             :  * A transaction with a bunch of additional info that only the owner cares about.
     322             :  * It includes any unrecorded transactions needed to link it back to the block chain.
     323             :  */
     324             : class CWalletTx
     325             : {
     326             : private:
     327             :     const CWallet* pwallet;
     328             : 
     329             :     /** Constant used in hashBlock to indicate tx has been abandoned, only used at
     330             :      * serialization/deserialization to avoid ambiguity with conflicted.
     331             :      */
     332             :     static const uint256 ABANDON_HASH;
     333             : 
     334             : public:
     335             :     mapValue_t mapValue;
     336             :     mapSaplingNoteData_t mapSaplingNoteData;
     337             :     std::vector<std::pair<std::string, std::string> > vOrderForm;
     338             :     unsigned int fTimeReceivedIsTxTime;
     339             :     unsigned int nTimeReceived; //! time received by this node
     340             :     /**
     341             :      * Stable timestamp representing the block time, for a transaction included in a block,
     342             :      * or else the time when the transaction was received if it isn't yet part of a block.
     343             :      */
     344             :     unsigned int nTimeSmart;
     345             :     char fFromMe;
     346             :     int64_t nOrderPos; //! position in ordered transaction list
     347             : 
     348             :     // memory only
     349             :     enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
     350             :     CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
     351             :     bool IsAmountCached(AmountType type, const isminefilter& filter) const; // Only used in unit tests
     352             :     mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
     353             : 
     354             :     mutable bool fStakeDelegationVoided;
     355             :     mutable bool fChangeCached;
     356             :     mutable bool fInMempool;
     357             :     mutable CAmount nChangeCached;
     358             :     mutable bool fShieldedChangeCached;
     359             :     mutable CAmount nShieldedChangeCached;
     360             : 
     361             :     CWalletTx(const CWallet* pwalletIn, CTransactionRef arg);
     362             :     void Init(const CWallet* pwalletIn);
     363             : 
     364             :     CTransactionRef tx;
     365             : 
     366             :     /* New transactions start as UNCONFIRMED. At BlockConnected,
     367             :      * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
     368             :      * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
     369             :      * block connection, we update conflicted tx and its dependencies as CONFLICTED.
     370             :      * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
     371             :      * by using the abandontransaction call. This last status may be override by a CONFLICTED
     372             :      * or CONFIRMED transition.
     373             :      */
     374             :     enum Status {
     375             :         UNCONFIRMED,
     376             :         CONFIRMED,
     377             :         CONFLICTED,
     378             :         ABANDONED
     379             :     };
     380             : 
     381             :     /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
     382             :      * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
     383             :      * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
     384             :      * and block height of the deepest conflicting tx.
     385             :      */
     386             :     struct Confirmation {
     387             :         Status status;
     388             :         int block_height;
     389             :         uint256 hashBlock;
     390             :         int nIndex;
     391     1405169 :         Confirmation(Status s = UNCONFIRMED, int b = 0, const uint256& h = UINT256_ZERO, int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
     392             :     };
     393             : 
     394             :     Confirmation m_confirm;
     395             : 
     396             :     template<typename Stream>
     397      336572 :     void Serialize(Stream& s) const
     398             :     {
     399      336572 :         mapValue_t mapValueCopy = mapValue;
     400             : 
     401      336572 :         mapValueCopy["fromaccount"] = "";
     402      336572 :         WriteOrderPos(nOrderPos, mapValueCopy);
     403      336572 :         if (nTimeSmart) {
     404      336570 :             mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
     405             :         }
     406             : 
     407      336572 :         std::vector<char> dummy_vector1; //!< Used to be vMerkleBranch
     408      336572 :         std::vector<char> dummy_vector2; //!< Used to be vtxPrev
     409      336572 :         char dummy_char = false; //!< Used to be fSpent
     410      336565 :         uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
     411      336552 :         int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
     412      336572 :         s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_char;
     413             : 
     414      336572 :         if (this->tx->isSaplingVersion()) {
     415      336572 :             s << mapSaplingNoteData;
     416             :         }
     417      336572 :     }
     418             : 
     419             :     template<typename Stream>
     420        6763 :     void Unserialize(Stream& s)
     421             :     {
     422        6763 :         Init(nullptr);
     423             : 
     424       13526 :         std::vector<uint256> dummy_vector1; //!< Used to be vMerkleBranch
     425        6763 :         std::vector<CMerkleTx> dummy_vector2; //!< Used to be vtxPrev
     426             :         char dummy_char; //! Used to be fSpent
     427             :         int serializedIndex;
     428       13526 :         s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_char;
     429             : 
     430        6763 :         if (this->tx->isSaplingVersion()) {
     431          29 :             s >> mapSaplingNoteData;
     432             :         }
     433             : 
     434             :         /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
     435             :          * the earliest block in the chain we know this or any in-wallet ancestor conflicts
     436             :          * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
     437             :          * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
     438             :          * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
     439             :          * compatibility (pre-commit 9ac63d6).
     440             :          */
     441        6763 :         if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
     442        6763 :             setAbandoned();
     443        6759 :         } else if (serializedIndex == -1) {
     444        6763 :             setConflicted();
     445       14470 :         } else if (!m_confirm.hashBlock.IsNull()) {
     446        6727 :             m_confirm.nIndex = serializedIndex;
     447        6763 :             setConfirmed();
     448             :         }
     449             : 
     450        6763 :         ReadOrderPos(nOrderPos, mapValue);
     451       20289 :         nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
     452             : 
     453       13526 :         mapValue.erase("fromaccount");
     454       13526 :         mapValue.erase("version");
     455       13526 :         mapValue.erase("spent");
     456       13526 :         mapValue.erase("n");
     457       13526 :         mapValue.erase("timesmart");
     458        6763 :     }
     459             : 
     460             :     void SetTx(CTransactionRef arg) { tx = std::move(arg); }
     461             : 
     462             :     //! make sure balances are recalculated
     463             :     void MarkDirty();
     464             : 
     465             :     void BindWallet(CWallet* pwalletIn);
     466             : 
     467             :     void SetSaplingNoteData(mapSaplingNoteData_t& noteData);
     468             : 
     469             :     Optional<std::pair<
     470             :             libzcash::SaplingNotePlaintext,
     471             :             libzcash::SaplingPaymentAddress>> DecryptSaplingNote(const SaplingOutPoint& op) const;
     472             : 
     473             :     Optional<std::pair<
     474             :             libzcash::SaplingNotePlaintext,
     475             :             libzcash::SaplingPaymentAddress>> RecoverSaplingNote(const SaplingOutPoint& op, const std::set<uint256>& ovks) const;
     476             : 
     477             :     //! checks whether a tx has P2CS inputs or not
     478             :     bool HasP2CSInputs() const;
     479             : 
     480             :     //! Store a comment
     481          19 :     void SetComment(const std::string& comment) { mapValue["comment"] = comment; }
     482             :     std::string GetComment() const {
     483             :         const auto& it = mapValue.find("comment");
     484             :         return it != mapValue.end() ? it->second : "";
     485             :     }
     486             : 
     487             :     int GetDepthAndMempool(bool& fConflicted) const;
     488             : 
     489             :     //! filter decides which addresses will count towards the debit
     490             :     CAmount GetDebit(const isminefilter& filter) const;
     491             :     CAmount GetCredit(const isminefilter& filter, bool recalculate = false) const;
     492             :     CAmount GetImmatureCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE_ALL) const;
     493             :     CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter=ISMINE_SPENDABLE) const;
     494             :     // Return sum of locked coins
     495             :     CAmount GetLockedCredit() const;
     496             :     CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
     497             :     CAmount GetAvailableWatchOnlyCredit(const bool fUseCache = true) const;
     498             :     CAmount GetChange() const;
     499             : 
     500             :     // Shielded credit/debit/change
     501             :     CAmount GetShieldedChange() const;
     502             :     CAmount GetShieldedAvailableCredit(bool fUseCache = true) const;
     503             : 
     504             :     // Cold staking contracts credit/debit
     505             :     CAmount GetColdStakingCredit(bool fUseCache = true) const;
     506             :     CAmount GetColdStakingDebit(bool fUseCache = true) const;
     507             :     CAmount GetStakeDelegationCredit(bool fUseCache = true) const;
     508             :     CAmount GetStakeDelegationDebit(bool fUseCache = true) const;
     509             : 
     510             :     void GetAmounts(std::list<COutputEntry>& listReceived,
     511             :                     std::list<COutputEntry>& listSent,
     512             :                     CAmount& nFee,
     513             :                     const isminefilter& filter) const;
     514             : 
     515             :     bool IsFromMe(const isminefilter& filter) const;
     516             : 
     517             :     bool InMempool() const;
     518             : 
     519             :     // True if only scriptSigs are different
     520             :     bool IsEquivalentTo(const CWalletTx& tx) const;
     521             : 
     522             :     bool IsTrusted() const;
     523             :     bool IsTrusted(int& nDepth, bool& fConflicted) const;
     524             : 
     525             :     int64_t GetTxTime() const;
     526             :     void UpdateTimeSmart();
     527             :     void RelayWalletTransaction(CConnman* connman);
     528             :     std::set<uint256> GetConflicts() const;
     529             : 
     530             :     /**
     531             :      * Return depth of transaction in blockchain:
     532             :      * <0  : conflicts with a transaction this deep in the blockchain
     533             :      *  0  : in memory pool, waiting to be included in a block
     534             :      * >=1 : this many blocks deep in the main chain
     535             :      */
     536             :     // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
     537             :     // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
     538             :     // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
     539             :     // resolve the issue of member access into incomplete type CWallet. Note
     540             :     // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
     541             :     // in place.
     542             :     int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
     543             :     bool IsInMainChainImmature() const;
     544             :     int GetBlocksToMaturity() const;
     545             : 
     546    14666601 :     bool isAbandoned() const { return m_confirm.status == CWalletTx::ABANDONED; }
     547          11 :     void setAbandoned()
     548             :     {
     549          11 :         m_confirm.status = CWalletTx::ABANDONED;
     550          11 :         m_confirm.hashBlock = UINT256_ZERO;
     551          11 :         m_confirm.block_height = 0;
     552          11 :         m_confirm.nIndex = 0;
     553           4 :     }
     554    13145676 :     bool isConflicted() const { return m_confirm.status == CWalletTx::CONFLICTED; }
     555          15 :     void setConflicted() { m_confirm.status = CWalletTx::CONFLICTED; }
     556    16221668 :     bool isUnconfirmed() const { return m_confirm.status == CWalletTx::UNCONFIRMED; }
     557         180 :     void setUnconfirmed() { m_confirm.status = CWalletTx::UNCONFIRMED; }
     558         179 :     bool isConfirmed() const { return m_confirm.status == CWalletTx::CONFIRMED; }
     559        6727 :     void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
     560             : 
     561     4007661 :     const uint256& GetHash() const { return tx->GetHash(); }
     562     7202801 :     bool IsCoinBase() const { return tx->IsCoinBase(); }
     563     5883573 :     bool IsCoinStake() const { return tx->IsCoinStake(); }
     564             : 
     565             :     /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
     566             :     bool AcceptToMemoryPool(CValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     567             : };
     568             : 
     569             : 
     570             : class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
     571             : 
     572             : /**
     573             :  * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
     574             :  * and provides the ability to create new transactions.
     575             :  */
     576             : class CWallet : public CCryptoKeyStore, public CValidationInterface
     577             : {
     578             : private:
     579             :     static std::atomic<bool> fFlushScheduled;
     580             :     std::atomic<bool> fAbortRescan;
     581             :     std::atomic<bool> fScanningWallet; //controlled by WalletRescanReserver
     582             :     std::mutex mutexScanning;
     583             :     friend class WalletRescanReserver;
     584             : 
     585             : 
     586             :     //! keeps track of whether Unlock has run a thorough check before
     587             :     bool fDecryptionThoroughlyChecked{false};
     588             : 
     589             :     //! Key manager //
     590             :     std::unique_ptr<ScriptPubKeyMan> m_spk_man = std::make_unique<ScriptPubKeyMan>(this);
     591             :     std::unique_ptr<SaplingScriptPubKeyMan> m_sspk_man = std::make_unique<SaplingScriptPubKeyMan>(this);
     592             : 
     593             :     //! the current wallet version: clients below this version are not able to load the wallet
     594             :     int nWalletVersion;
     595             : 
     596             :     //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
     597             :     int nWalletMaxVersion;
     598             : 
     599             :     /**
     600             :      * Wallet filename from wallet=<path> command line or config option.
     601             :      * Used in debug logs and to send RPCs to the right wallet instance when
     602             :      * more than one wallet is loaded.
     603             :      */
     604             :     std::string m_name;
     605             : 
     606             :     /** Internal database handle. */
     607             :     std::unique_ptr<WalletDatabase> database;
     608             : 
     609             :     /**
     610             :      * The following is used to keep track of how far behind the wallet is
     611             :      * from the chain sync, and to allow clients to block on us being caught up.
     612             :      *
     613             :      * Note that this is *not* how far we've processed, we may need some rescan
     614             :      * to have seen all transactions in the chain, but is only used to track
     615             :      * live BlockConnected callbacks.
     616             :      *
     617             :      * Protected by cs_main (see BlockUntilSyncedToCurrentChain)
     618             :      */
     619             :     uint256 m_last_block_processed GUARDED_BY(cs_wallet) = UINT256_ZERO;
     620             : 
     621             :     /* Height of last block processed is used by wallet to know depth of transactions
     622             :     * without relying on Chain interface beyond asynchronous updates. For safety, we
     623             :     * initialize it to -1. Height is a pointer on node's tip and doesn't imply
     624             :     * that the wallet has scanned sequentially all blocks up to this one.
     625             :     */
     626             :     int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
     627             :     int64_t m_last_block_processed_time GUARDED_BY(cs_wallet) = 0;
     628             : 
     629             :     int64_t nNextResend;
     630             :     int64_t nLastResend;
     631             :     std::atomic<int64_t> nTimeBestReceived{0}; // Used only to inform the wallet of when we last received a block
     632             : 
     633             :     /**
     634             :      * Used to keep track of spent outpoints, and
     635             :      * detect and report conflicts (double-spends or
     636             :      * mutated transactions where the mutant gets mined).
     637             :      */
     638             :     typedef TxSpendMap<COutPoint> TxSpends;
     639             :     TxSpends mapTxSpends;
     640             :     void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
     641             :     void AddToSpends(const uint256& wtxid);
     642             : 
     643             :     /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
     644             :     void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
     645             : 
     646             :     template <class T>
     647             :     void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range);
     648             :     void ChainTipAdded(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree saplingTree);
     649             : 
     650             :     /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected */
     651             :     void SyncTransaction(const CTransactionRef& tx, const CWalletTx::Confirmation& confirm);
     652             : 
     653             :     bool IsKeyUsed(const CPubKey& vchPubKey) const;
     654             : 
     655             :     struct OutputAvailabilityResult
     656             :     {
     657             :         bool available{false};
     658             :         bool solvable{false};
     659             :         bool spendable{false};
     660             :     };
     661             : 
     662             :     OutputAvailabilityResult CheckOutputAvailability(const CTxOut& output,
     663             :                                                      const unsigned int outIndex,
     664             :                                                      const uint256& wtxid,
     665             :                                                      const CCoinControl* coinControl,
     666             :                                                      const bool fCoinsSelected,
     667             :                                                      const bool fIncludeColdStaking,
     668             :                                                      const bool fIncludeDelegated,
     669             :                                                      const bool fIncludeLocked) const;
     670             : 
     671             :     /** Return the selected known outputs */
     672             :     std::vector<COutput> GetOutputsFromCoinControl(const CCoinControl* coinControl);
     673             : 
     674             :     //! Destination --> label/purpose mapping.
     675             :     std::map<CWDestination, AddressBook::CAddressBookData> mapAddressBook;
     676             : 
     677             : public:
     678             : 
     679             :     static const CAmount DEFAULT_STAKE_SPLIT_THRESHOLD = 500 * COIN;
     680             : 
     681             :     //! Generates hd wallet //
     682             :     bool SetupSPKM(bool newKeypool = true, bool memOnly = false);
     683             :     //! Whether the wallet is hd or not //
     684             :     bool IsHDEnabled() const;
     685             :     //! Whether the wallet supports Sapling or not //
     686             :     bool IsSaplingUpgradeEnabled() const;
     687             : 
     688             :     /** Get last block processed height */
     689    17349751 :     int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
     690             :     {
     691    17349751 :         AssertLockHeld(cs_wallet);
     692    17349751 :         assert(m_last_block_processed_height >= 0);
     693    17349751 :         return m_last_block_processed_height;
     694             :     };
     695             :     /** Get last block processed height locking the wallet */
     696             :     int GetLastBlockHeightLockWallet() const;
     697             :     /** Set last block processed height, currently only use in unit test */
     698           9 :     void SetLastBlockProcessed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
     699             :     {
     700           9 :         AssertLockHeld(cs_wallet);
     701           9 :         m_last_block_processed_height = pindex->nHeight;
     702           9 :         m_last_block_processed = pindex->GetBlockHash();
     703           9 :         m_last_block_processed_time = pindex->GetBlockTime();
     704             :     };
     705             : 
     706             :     /* SPKM Helpers */
     707             :     const CKeyingMaterial& GetEncryptionKey() const;
     708             :     bool HasEncryptionKeys() const;
     709             : 
     710             :     //! Get spkm
     711             :     ScriptPubKeyMan* GetScriptPubKeyMan() const;
     712     1571612 :     SaplingScriptPubKeyMan* GetSaplingScriptPubKeyMan() const { return m_sspk_man.get(); }
     713             : 
     714             :     bool HasSaplingSPKM() const;
     715             : 
     716             :     /*
     717             :      * Main wallet lock.
     718             :      * This lock protects all the fields added by CWallet.
     719             :      */
     720             :     mutable RecursiveMutex cs_wallet;
     721             : 
     722             :     bool fWalletUnlockStaking;
     723             : 
     724             :     WalletBatch* encrypted_batch;
     725             : 
     726             :     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
     727             : 
     728             :     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
     729             :     MasterKeyMap mapMasterKeys;
     730             :     unsigned int nMasterKeyMaxID;
     731             : 
     732             :     // Stake split threshold
     733             :     CAmount nStakeSplitThreshold;
     734             :     // minimum value allowed for nStakeSplitThreshold (customizable with -minstakesplit flag)
     735             :     static CAmount minStakeSplitThreshold;
     736             :     // Staker status (last hashed block and time)
     737             :     CStakerStatus* pStakerStatus = nullptr;
     738             : 
     739             :     // User-defined fee PIV/kb
     740             :     bool fUseCustomFee;
     741             :     CAmount nCustomFee;
     742             : 
     743             :     //Auto Combine Inputs
     744             :     bool fCombineDust;
     745             :     CAmount nAutoCombineThreshold;
     746             :     int frequency;
     747             : 
     748             :     /** Get database handle used by this wallet. Ideally this function would
     749             :      * not be necessary.
     750             :      */
     751             :     WalletDatabase* GetDBHandlePtr() const { return database.get(); }
     752       62519 :     WalletDatabase& GetDBHandle() const { return *database; }
     753             : 
     754             :     /** Get a name for this wallet for logging/debugging purposes.
     755             :      */
     756         185 :     const std::string& GetName() const { return m_name; }
     757             : 
     758             :     /** Get the path to the wallet's db file */
     759             :     fs::path GetPathToDBFile() { return database->GetPathToFile(); }
     760             : 
     761             :     /** Construct wallet with specified name and database implementation. */
     762             :     CWallet(std::string name, std::unique_ptr<WalletDatabase> dbw_in);
     763             :     ~CWallet();
     764             :     void SetNull();
     765             : 
     766             :     std::map<uint256, CWalletTx> mapWallet;
     767             : 
     768             :     typedef std::multimap<int64_t, CWalletTx*> TxItems;
     769             :     TxItems wtxOrdered;
     770             : 
     771             :     int64_t nOrderPosNext;
     772             : 
     773             :     std::set<COutPoint> setLockedCoins;
     774             :     std::set<SaplingOutPoint> setLockedNotes;
     775             : 
     776             :     int64_t nTimeFirstKey;
     777             : 
     778             :     // Public SyncMetadata interface used for the sapling spent nullifier map.
     779             :     void SyncMetaDataN(std::pair<TxSpendMap<uint256>::iterator, TxSpendMap<uint256>::iterator> range);
     780             : 
     781             :     const CWalletTx* GetWalletTx(const uint256& hash) const;
     782             : 
     783             :     std::vector<CWalletTx> getWalletTxs();
     784             :     std::string GetUniqueWalletBackupName() const;
     785             : 
     786             :     //! check whether we are allowed to upgrade (or already support) to the named feature
     787             :     bool CanSupportFeature(enum WalletFeature wf);
     788             : 
     789             :     struct AvailableCoinsFilter {
     790             :         public:
     791         659 :         AvailableCoinsFilter() {}
     792        2081 :         AvailableCoinsFilter(bool _fIncludeDelegated,
     793             :                              bool _fIncludeColdStaking,
     794             :                              bool _fOnlySafe,
     795             :                              bool _fOnlySpendable,
     796             :                              std::set<CTxDestination>* _onlyFilteredDest,
     797             :                              int _minDepth,
     798             :                              bool _fIncludeLocked = false,
     799        2081 :                              CAmount _nMaxOutValue = 0) :
     800             :                 fIncludeDelegated(_fIncludeDelegated),
     801             :                 fIncludeColdStaking(_fIncludeColdStaking),
     802             :                 fOnlySafe(_fOnlySafe),
     803             :                 fOnlySpendable(_fOnlySpendable),
     804             :                 onlyFilteredDest(_onlyFilteredDest),
     805             :                 minDepth(_minDepth),
     806             :                 fIncludeLocked(_fIncludeLocked),
     807        2081 :                 nMaxOutValue(_nMaxOutValue) {}
     808             : 
     809             :         bool fIncludeDelegated{true};
     810             :         bool fIncludeColdStaking{false};
     811             :         bool fOnlySafe{true};
     812             :         bool fOnlySpendable{false};
     813             :         std::set<CTxDestination>* onlyFilteredDest{nullptr};
     814             :         int minDepth{0};
     815             :         bool fIncludeLocked{false};
     816             :         // Select outputs with value <= nMaxOutValue
     817             :         CAmount nMaxOutValue{0}; // 0 means not active
     818             :         CAmount nMinOutValue{0}; // 0 means not active
     819             :         CAmount nMinimumSumAmount{0}; // 0 means not active
     820             :         unsigned int nMaximumCount{0}; // 0 means not active
     821             :     };
     822             : 
     823             :     /**
     824             :      * populate vCoins with vector of available COutputs.
     825             :      */
     826             :     bool AvailableCoins(std::vector<COutput>* pCoins,   // --> populates when != nullptr
     827             :                         const CCoinControl* coinControl = nullptr,
     828             :                         AvailableCoinsFilter coinsFilter = AvailableCoinsFilter()
     829             :                         ) const;
     830             :     //! >> Available coins (spending)
     831             :     bool SelectCoinsToSpend(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl = nullptr) const;
     832             : 
     833             :     /**
     834             :      * Select coins until nTargetValue is reached. Return the actual value
     835             :      * and the corresponding coin set.
     836             :      */
     837             :     bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const;
     838             :     //! >> Available coins (staking)
     839             :     bool StakeableCoins(std::vector<CStakeableOutput>* pCoins = nullptr);
     840             :     //! >> Available coins (P2CS)
     841             :     void GetAvailableP2CSCoins(std::vector<COutput>& vCoins) const;
     842             : 
     843             :     std::map<CTxDestination, std::vector<COutput> > AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue, bool fIncludeColdStaking);
     844             : 
     845             :     /**
     846             :      * Return list of available coins and locked coins grouped by non-change output address.
     847             :      * PIVX: group coins by pair <CTxDestination, Optional<CTxDestination>>. The optional destination
     848             :      * is reserved for the staker address in case of P2CS.
     849             :      */
     850             :     std::map<std::pair<CTxDestination, Optional<CTxDestination>>, std::vector<COutput>> ListCoins() const;
     851             :     /**
     852             :      * Return list of available shield notes and locked shield notes grouped by sapling address.
     853             :      */
     854             :     std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>> ListNotes() const;
     855             : 
     856             :     /// Get 10000 PIV output and keys which can be used for the Masternode
     857             :     bool GetMasternodeVinAndKeys(CPubKey& pubKeyRet,
     858             :                                  CKey& keyRet,
     859             :                                  const COutPoint& collateralOut,
     860             :                                  bool fValidateCollateral,
     861             :                                  std::string& strError);
     862             : 
     863             :     bool IsSaplingSpent(const SaplingOutPoint& op) const;
     864             :     bool IsSpent(const COutPoint& outpoint) const;
     865             :     bool IsSpent(const uint256& hash, unsigned int n) const;
     866             : 
     867             :     bool IsLockedCoin(const uint256& hash, unsigned int n) const;
     868             :     bool IsLockedNote(const SaplingOutPoint& op) const;
     869             : 
     870             :     void LockCoin(const COutPoint& output);
     871             :     void LockNote(const SaplingOutPoint& op);
     872             : 
     873             :     void UnlockCoin(const COutPoint& output);
     874             :     void UnlockNote(const SaplingOutPoint& op);
     875             : 
     876             :     void UnlockAllCoins();
     877             :     void UnlockAllNotes();
     878             : 
     879             :     std::set<COutPoint> ListLockedCoins();
     880             :     std::set<SaplingOutPoint> ListLockedNotes();
     881             : 
     882             :     /*
     883             :      * Rescan abort properties
     884             :      */
     885           0 :     void AbortRescan() { fAbortRescan = true; }
     886           2 :     bool IsAbortingRescan() { return fAbortRescan; }
     887           0 :     bool IsScanning() { return fScanningWallet; }
     888             : 
     889             :     /*
     890             :      * Stake Split threshold
     891             :      */
     892             :     bool SetStakeSplitThreshold(const CAmount sst);
     893           0 :     CAmount GetStakeSplitThreshold() const { LOCK(cs_wallet); return nStakeSplitThreshold; }
     894             : 
     895             :     /*
     896             :      *  Requires cs_wallet lock.
     897             :      *  Lock for spending the coin c, if it's owned by the wallet, it's unspent, and:
     898             :      *  -- If ptx is not null, c is one of the outputs of *ptx
     899             :      *  -- If ptx is null, c is the output of a transaction in mapWallet
     900             :      */
     901             :     void LockOutpointIfMine(const CTransactionRef& ptx, const COutPoint& c);
     902             :     /*
     903             :      * Same functionality as above but locking the cs_wallet mutex internally.
     904             :      * future: add capability to lock the mutex from outside of this class without exposing it.
     905             :      */
     906             :     void LockOutpointIfMineWithMutex(const CTransactionRef& ptx, const COutPoint& c);
     907             : 
     908             :     /*
     909             :      *  Requires cs_wallet lock.
     910             :      *  Called from AddToWalletIfInvolvingMe. If ptx is a ProRegTx, and the
     911             :      *  collateral (either referenced or created) is owned by this wallet,
     912             :      *  lock the corresponding coin, to prevent accidental spending.
     913             :      */
     914             :     void LockIfMyCollateral(const CTransactionRef& ptx);
     915             : 
     916             :     //  keystore implementation
     917             :     CallResult<CTxDestination> getNewAddress(const std::string& addressLabel, const std::string purpose,
     918             :                                              const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
     919             :     CallResult<CTxDestination> getNewAddress(const std::string& label);
     920             :     CallResult<CTxDestination> getNewStakingAddress(const std::string& label);
     921             :     int64_t GetKeyCreationTime(const CWDestination& dest);
     922             :     int64_t GetKeyCreationTime(CPubKey pubkey);
     923             :     int64_t GetKeyCreationTime(const CTxDestination& address);
     924             :     int64_t GetKeyCreationTime(const libzcash::SaplingPaymentAddress& address);
     925             : 
     926             :     //////////// Sapling //////////////////
     927             : 
     928             :     // Search for notes and addresses from this wallet in the tx, and add the addresses --> IVK mapping to the keystore if missing.
     929             :     bool FindNotesDataAndAddMissingIVKToKeystore(const CTransaction& tx, Optional<mapSaplingNoteData_t>& saplingNoteData);
     930             :     // Decrypt sapling output notes with the inputs ovk and updates saplingNoteDataMap
     931             :     void AddExternalNotesDataToTx(CWalletTx& wtx) const;
     932             : 
     933             :     //! Generates new Sapling key
     934             :     libzcash::SaplingPaymentAddress GenerateNewSaplingZKey(std::string label = "");
     935             : 
     936             :     //! pindex is the new tip being connected.
     937             :     void IncrementNoteWitnesses(const CBlockIndex* pindex,
     938             :                                 const CBlock* pblock,
     939             :                                 SaplingMerkleTree& saplingTree);
     940             : 
     941             :     //! pindex is the old tip being disconnected.
     942             :     void DecrementNoteWitnesses(const CBlockIndex* pindex);
     943             : 
     944             :     //! clear note witness cache
     945             :     void ClearNoteWitnessCache();
     946             : 
     947             : 
     948             :     //! Adds Sapling spending key to the store, and saves it to disk
     949             :     bool AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key);
     950             :     bool AddSaplingIncomingViewingKeyW(
     951             :             const libzcash::SaplingIncomingViewingKey &ivk,
     952             :             const libzcash::SaplingPaymentAddress &addr);
     953             :     bool AddCryptedSaplingSpendingKeyW(
     954             :             const libzcash::SaplingExtendedFullViewingKey &extfvk,
     955             :             const std::vector<unsigned char> &vchCryptedSecret);
     956             :     //! Returns true if the wallet contains the spending key
     957             :     bool HaveSpendingKeyForPaymentAddress(const libzcash::SaplingPaymentAddress &zaddr) const;
     958             : 
     959             : 
     960             :     //! Adds spending key to the store, without saving it to disk (used by LoadWallet)
     961             :     bool LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key);
     962             :     //! Load spending key metadata (used by LoadWallet)
     963             :     bool LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta);
     964             :     //! Adds a Sapling payment address -> incoming viewing key map entry,
     965             :     //! without saving it to disk (used by LoadWallet)
     966             :     bool LoadSaplingPaymentAddress(
     967             :             const libzcash::SaplingPaymentAddress &addr,
     968             :             const libzcash::SaplingIncomingViewingKey &ivk);
     969             :     //! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
     970             :     bool LoadCryptedSaplingZKey(const libzcash::SaplingExtendedFullViewingKey &extfvk,
     971             :                                 const std::vector<unsigned char> &vchCryptedSecret);
     972             : 
     973             :     //////////// End Sapling //////////////
     974             : 
     975             :     //! Adds a key to the store, and saves it to disk.
     976             :     bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey) override;
     977             :     //! Adds a key to the store, without saving it to disk (used by LoadWallet)
     978        7787 :     bool LoadKey(const CKey& key, const CPubKey& pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
     979             :     //! Load metadata (used by LoadWallet)
     980             :     bool LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& metadata);
     981             : 
     982             :     bool LoadMinVersion(int nVersion);
     983             :     void UpdateTimeFirstKey(int64_t nCreateTime);
     984             : 
     985             :     //! Adds an encrypted key to the store, and saves it to disk.
     986             :     bool AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) override;
     987             :     //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
     988             :     bool LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret);
     989             :     bool AddCScript(const CScript& redeemScript) override;
     990             :     bool LoadCScript(const CScript& redeemScript);
     991             : 
     992             :     //! Adds a destination data tuple to the store, and saves it to disk
     993             :     bool AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value);
     994             :     //! Erases a destination data tuple in the store and on disk
     995             :     bool EraseDestData(const CTxDestination& dest, const std::string& key);
     996             :     //! Adds a destination data tuple to the store, without saving it to disk
     997             :     bool LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value);
     998             :     //! Get all destination values matching a prefix.
     999             :     std::vector<std::string> GetDestValues(const std::string& prefix) const;
    1000             : 
    1001             :     //! Adds a watch-only address to the store, and saves it to disk.
    1002             :     bool AddWatchOnly(const CScript& dest) override;
    1003             :     bool RemoveWatchOnly(const CScript& dest) override;
    1004             :     //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
    1005             :     bool LoadWatchOnly(const CScript& dest);
    1006             : 
    1007             :     //! Lock Wallet
    1008             :     //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
    1009             :     int64_t nRelockTime;
    1010             :     bool Lock();
    1011             :     bool Unlock(const SecureString& strWalletPassphrase, bool anonimizeOnly = false);
    1012             :     bool Unlock(const CKeyingMaterial& vMasterKeyIn);
    1013             : 
    1014             :     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
    1015             :     bool EncryptWallet(const SecureString& strWalletPassphrase);
    1016             : 
    1017             :     std::vector<CKeyID> GetAffectedKeys(const CScript& spk);
    1018             :     void GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    1019             : 
    1020             :     /**
    1021             :      * Increment the next transaction order id
    1022             :      * @return next transaction order id
    1023             :      */
    1024             :     int64_t IncOrderPosNext(WalletBatch* batch = nullptr);
    1025             : 
    1026             :     void MarkDirty();
    1027             :     bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose = true);
    1028             :     bool LoadToWallet(CWalletTx& wtxIn);
    1029             :     void TransactionAddedToMempool(const CTransactionRef& tx) override;
    1030             :     void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex) override;
    1031             :     void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const uint256& blockHash, int nBlockHeight, int64_t blockTime) override;
    1032             :     bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CWalletTx::Confirmation& confirm, bool fUpdate);
    1033             :     void EraseFromWallet(const uint256& hash);
    1034             : 
    1035             :     /**
    1036             :      * Upgrade wallet to HD and Sapling if needed. Does nothing if not.
    1037             :      */
    1038             :     bool Upgrade(std::string& error, const int prevVersion);
    1039             :     bool ActivateSaplingWallet(bool memOnly = false);
    1040             : 
    1041             :     int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
    1042             :     CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, const WalletRescanReserver& reserver, bool fUpdate = false, bool fromStartup = false);
    1043             :     void TransactionRemovedFromMempool(const CTransactionRef &ptx, MemPoolRemovalReason reason) override;
    1044             :     void ReacceptWalletTransactions(bool fFirstLoad = false);
    1045             :     void ResendWalletTransactions(CConnman* connman) override;
    1046             :     void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override;
    1047             : 
    1048             :     struct Balance {
    1049             :         CAmount m_mine_trusted{0};               //!< Trusted, at depth=GetBalance.min_depth or more
    1050             :         CAmount m_mine_untrusted_pending{0};     //!< Untrusted, but in mempool (pending)
    1051             :         CAmount m_mine_immature{0};              //!< Immature coinbases/coinstakes in the main chain
    1052             :         CAmount m_mine_trusted_shield{0};        //!< Trusted shield, at depth=GetBalance.min_depth or more
    1053             :         CAmount m_mine_untrusted_shielded_balance{0}; //!< Untrusted shield, but in mempool (pending)
    1054             :         CAmount m_mine_cs_delegated_trusted{0};  //!< Trusted, at depth=GetBalance.min_depth or more. Part of m_mine_trusted as well
    1055             :     };
    1056             :     Balance GetBalance(int min_depth = 0) const;
    1057             : 
    1058             :     CAmount loopTxsBalance(const std::function<void(const uint256&, const CWalletTx&, CAmount&)>&method) const;
    1059             :     CAmount GetAvailableBalance(bool fIncludeDelegated = true, bool fIncludeShielded = true) const;
    1060             :     CAmount GetAvailableBalance(isminefilter& filter, bool useCache = false, int minDepth = 1) const;
    1061             :     CAmount GetColdStakingBalance() const;  // delegated coins for which we have the staking key
    1062             :     CAmount GetImmatureColdStakingBalance() const;
    1063             :     CAmount GetStakingBalance(const bool fIncludeColdStaking = true) const;
    1064             :     CAmount GetDelegatedBalance() const;    // delegated coins for which we have the spending key
    1065             :     CAmount GetImmatureDelegatedBalance() const;
    1066             :     CAmount GetLockedCoins() const;
    1067             :     CAmount GetLockedShieldCoins() const;
    1068             :     CAmount GetUnconfirmedBalance(isminetype filter = ISMINE_SPENDABLE_ALL) const;
    1069             :     CAmount GetImmatureBalance() const;
    1070             :     CAmount GetWatchOnlyBalance() const;
    1071             :     CAmount GetUnconfirmedWatchOnlyBalance() const;
    1072             :     CAmount GetImmatureWatchOnlyBalance() const;
    1073             :     CAmount GetLegacyBalance(const isminefilter& filter, int minDepth) const;
    1074             :     bool FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, const CTxDestination& destChange = CNoDestination());
    1075             :     /**
    1076             :      * Create a new transaction paying the recipients with a set of coins
    1077             :      * selected by SelectCoins(); Also create the change output, when needed
    1078             :      * @note passing nChangePosInOut as -1 will result in setting a random position
    1079             :      */
    1080             :     bool CreateTransaction(const std::vector<CRecipient>& vecSend,
    1081             :         CTransactionRef& txRet,
    1082             :         CReserveKey& reservekey,
    1083             :         CAmount& nFeeRet,
    1084             :         int& nChangePosInOut,
    1085             :         std::string& strFailReason,
    1086             :         const CCoinControl* coinControl = nullptr,
    1087             :         bool sign = true,
    1088             :         CAmount nFeePay = 0,
    1089             :         bool fIncludeDelegated = false,
    1090             :         bool* fStakeDelegationVoided = nullptr,
    1091             :         int nExtraSize = 0,
    1092             :         int nMinDepth = 0);
    1093             : 
    1094             :     bool CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = nullptr, CAmount nFeePay = 0, bool fIncludeDelegated = false, bool* fStakeDelegationVoided = nullptr, int nExtraSize = 0, int nMinDepth = 0);
    1095             : 
    1096             :     // enumeration for CommitResult (return status of CommitTransaction)
    1097             :     enum CommitStatus
    1098             :     {
    1099             :         OK,
    1100             :         Abandoned,              // Failed to accept to memory pool. Successfully removed from the wallet.
    1101             :         NotAccepted,            // Failed to accept to memory pool. Unable to abandon.
    1102             :     };
    1103        1441 :     struct CommitResult
    1104             :     {
    1105        1441 :         CommitResult(): status(CommitStatus::NotAccepted) {}
    1106             :         CWallet::CommitStatus status;
    1107             :         CValidationState state;
    1108             :         uint256 hashTx = UINT256_ZERO;
    1109             :         // converts CommitResult in human-readable format
    1110             :         std::string ToString() const;
    1111             :     };
    1112             :     CWallet::CommitResult CommitTransaction(CTransactionRef tx, CReserveKey& opReservekey, CConnman* connman);
    1113             :     CWallet::CommitResult CommitTransaction(CTransactionRef tx, CReserveKey* reservekey, CConnman* connman, mapValue_t* extraValues=nullptr);
    1114             : 
    1115             :     bool CreateCoinstakeOuts(const CPivStake& stakeInput, std::vector<CTxOut>& vout, CAmount nTotal) const;
    1116             :     bool CreateCoinStake(const CBlockIndex* pindexPrev,
    1117             :                          unsigned int nBits,
    1118             :                          CMutableTransaction& txNew,
    1119             :                          int64_t& nTxNewTime,
    1120             :                          std::vector<CStakeableOutput>* availableCoins,
    1121             :                          bool stopOnNewBlock = true) const;
    1122             :     bool SignCoinStake(CMutableTransaction& txNew) const;
    1123             :     void AutoCombineDust(CConnman* connman);
    1124             : 
    1125             :     // Shielded balances
    1126             :     CAmount GetAvailableShieldedBalance(bool fUseCache = true) const;
    1127             :     CAmount GetUnconfirmedShieldedBalance() const;
    1128             : 
    1129             :     static CFeeRate minTxFee;
    1130             : 
    1131             :     size_t KeypoolCountExternalKeys();
    1132             :     bool TopUpKeyPool(unsigned int kpSize = 0);
    1133             :     void KeepKey(int64_t nIndex);
    1134             :     void ReturnKey(int64_t nIndex, const bool internal = false, const bool staking = false);
    1135             :     bool GetKeyFromPool(CPubKey& key, const uint8_t& type = HDChain::ChangeType::EXTERNAL);
    1136             :     int64_t GetOldestKeyPoolTime();
    1137             : 
    1138             :     std::set<std::set<CTxDestination> > GetAddressGroupings();
    1139             :     std::map<CTxDestination, CAmount> GetAddressBalances();
    1140             : 
    1141             :     std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
    1142             : 
    1143             :     bool CreateBudgetFeeTX(CTransactionRef& tx, const uint256& hash, CReserveKey& keyChange, CAmount fee);
    1144             : 
    1145             :     bool IsUsed(const CTxDestination address) const;
    1146             :     bool IsUsed(const libzcash::SaplingPaymentAddress address) const;
    1147             : 
    1148             :     isminetype IsMine(const CTxIn& txin) const;
    1149             :     CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
    1150             :     isminetype IsMine(const CTxOut& txout) const;
    1151             :     CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
    1152             :     bool IsChange(const CTxOut& txout) const;
    1153             :     bool IsChange(const CTxDestination& address) const;
    1154             :     CAmount GetChange(const CTxOut& txout) const;
    1155             :     bool IsMine(const CTransactionRef& tx) const;
    1156             :     /** should probably be renamed to IsRelevantToMe */
    1157             :     bool IsFromMe(const CTransactionRef& tx) const;
    1158             :     CAmount GetDebit(const CTransactionRef& tx, const isminefilter& filter) const;
    1159             :     CAmount GetCredit(const CWalletTx& tx, const isminefilter& filter) const;
    1160             :     CAmount GetChange(const CTransactionRef& tx) const;
    1161             : 
    1162             :     void SetBestChain(const CBlockLocator& loc) override;
    1163             :     void SetBestChainInternal(WalletBatch& batch, const CBlockLocator& loc); // only public for testing purposes, must never be called directly in any other situation
    1164             :     // Force balance recomputation if any transaction got conflicted
    1165             :     void MarkAffectedTransactionsDirty(const CTransaction& tx); // only public for testing purposes, must never be called directly in any other situation
    1166             : 
    1167             :     DBErrors LoadWallet(bool& fFirstRunRet);
    1168             :     DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
    1169             : 
    1170             :     static std::string ParseIntoAddress(const CWDestination& dest, const std::string& purpose);
    1171             : 
    1172             :     bool SetAddressBook(const CWDestination& address, const std::string& strName, const std::string& purpose);
    1173             :     bool DelAddressBook(const CWDestination& address, const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS);
    1174             :     bool HasAddressBook(const CWDestination& address) const;
    1175             :     bool HasDelegator(const CTxOut& out) const;
    1176         361 :     int GetAddressBookSize() const { return mapAddressBook.size(); };
    1177             : 
    1178         146 :     CAddressBookIterator NewAddressBookIterator() { return CAddressBookIterator(mapAddressBook); }
    1179             :     std::string GetPurposeForAddressBookEntry(const CWDestination& address) const;
    1180             :     std::string GetNameForAddressBookEntry(const CWDestination& address) const;
    1181             :     Optional<AddressBook::CAddressBookData> GetAddressBookEntry(const CWDestination& address) const;
    1182             : 
    1183             :     void LoadAddressBookName(const CWDestination& dest, const std::string& strName);
    1184             :     void LoadAddressBookPurpose(const CWDestination& dest, const std::string& strPurpose);
    1185             : 
    1186             :     unsigned int GetKeyPoolSize();
    1187             :     unsigned int GetStakingKeyPoolSize();
    1188             : 
    1189             :     //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
    1190             :     bool SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false);
    1191             : 
    1192             :     //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
    1193             :     bool SetMaxVersion(int nVersion);
    1194             : 
    1195             :     //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
    1196             :     int GetVersion();
    1197             : 
    1198             :     //! Get wallet transactions that conflict with given transaction (spend same outputs)
    1199             :     std::set<uint256> GetConflicts(const uint256& txid) const;
    1200             : 
    1201             :     //! Flush wallet (bitdb flush)
    1202             :     void Flush(bool shutdown=false);
    1203             : 
    1204             :     /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
    1205             :     bool AbandonTransaction(const uint256& hashTx);
    1206             : 
    1207             :     /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
    1208             :     static CWallet* CreateWalletFromFile(const std::string& name, const fs::path& path);
    1209             : 
    1210             :     /**
    1211             :      * Wallet post-init setup
    1212             :      * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
    1213             :      */
    1214             :     void postInitProcess(CScheduler& scheduler);
    1215             : 
    1216             :     /**
    1217             :      * Creates a wallet backup in strDest path
    1218             :      */
    1219             :     bool BackupWallet(const std::string& strDest);
    1220             : 
    1221             :     /**
    1222             :      * Blocks until the wallet state is up-to-date to /at least/ the current
    1223             :      * chain at the time this function is entered
    1224             :      * Obviously holding cs_main/cs_wallet when going into this call may cause
    1225             :      * deadlock
    1226             :      */
    1227             :     void BlockUntilSyncedToCurrentChain();
    1228             : 
    1229             :     /**
    1230             :      * Address book entry changed.
    1231             :      * @note called with lock cs_wallet held.
    1232             :      */
    1233             :     boost::signals2::signal<void(CWallet* wallet, const CWDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status)> NotifyAddressBookChanged;
    1234             : 
    1235             :     /**
    1236             :      * Wallet transaction added, removed or updated.
    1237             :      * @note called with lock cs_wallet held.
    1238             :      */
    1239             :     boost::signals2::signal<void(CWallet* wallet, const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
    1240             : 
    1241             :     /** Show progress e.g. for rescan */
    1242             :     boost::signals2::signal<void(const std::string& title, int nProgress)> ShowProgress;
    1243             : 
    1244             :     /** Watch-only address added */
    1245             :     boost::signals2::signal<void(bool fHaveWatchOnly)> NotifyWatchonlyChanged;
    1246             : 
    1247             :     /** notify wallet file backed up */
    1248             :     boost::signals2::signal<void (const bool fSuccess, const std::string& filename)> NotifyWalletBacked;
    1249             : 
    1250             :     /** notify stake-split threshold changed */
    1251             :     boost::signals2::signal<void (const CAmount stakeSplitThreshold)> NotifySSTChanged;
    1252             : };
    1253             : 
    1254             : /** A key allocated from the key pool. */
    1255             : class CReserveKey
    1256             : {
    1257             : protected:
    1258             :     CWallet* pwallet;
    1259             :     int64_t nIndex;
    1260             :     bool internal{false};
    1261             :     CPubKey vchPubKey;
    1262             : 
    1263             : public:
    1264        4213 :     explicit CReserveKey(CWallet* pwalletIn)
    1265        4213 :     {
    1266        4213 :         nIndex = -1;
    1267        4213 :         pwallet = pwalletIn;
    1268             :     }
    1269             : 
    1270             :     CReserveKey() = default;
    1271             :     CReserveKey(const CReserveKey&) = delete;
    1272             :     CReserveKey& operator=(const CReserveKey&) = delete;
    1273             : 
    1274        4213 :     ~CReserveKey()
    1275        4211 :     {
    1276        4213 :         ReturnKey();
    1277           2 :     }
    1278             : 
    1279             :     void ReturnKey();
    1280             :     bool GetReservedKey(CPubKey& pubkey, bool internal = false);
    1281             :     void KeepKey();
    1282             : };
    1283             : 
    1284             : class COutput
    1285             : {
    1286             : public:
    1287             :     const CWalletTx* tx;
    1288             :     int i;
    1289             :     int nDepth;
    1290             : 
    1291             :     /** Whether we have the private keys to spend this output */
    1292             :     bool fSpendable;
    1293             : 
    1294             :     /** Whether we know how to spend this output, ignoring the lack of keys */
    1295             :     bool fSolvable;
    1296             : 
    1297             :     /**
    1298             :      * Whether this output is considered safe to spend. Unconfirmed transactions
    1299             :      * from outside keys and unconfirmed replacement transactions are considered
    1300             :      * unsafe and will not be used to fund new spending transactions.
    1301             :      */
    1302             :     bool fSafe;
    1303             : 
    1304     3671796 :     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn) :
    1305     3343363 :         tx(txIn), i(iIn), nDepth(nDepthIn), fSpendable(fSpendableIn), fSolvable(fSolvableIn), fSafe(fSafeIn)
    1306             :     {}
    1307             : 
    1308     6795230 :     CAmount Value() const { return tx->tx->vout[i].nValue; }
    1309             :     std::string ToString() const;
    1310             : };
    1311             : 
    1312             : class CStakeableOutput : public COutput
    1313             : {
    1314             : public:
    1315             :     const CBlockIndex* pindex{nullptr};
    1316             : 
    1317             :     CStakeableOutput(const CWalletTx* txIn, int iIn, int nDepthIn,
    1318             :                      const CBlockIndex*& pindex);
    1319             : 
    1320             : };
    1321             : 
    1322             : /** RAII object to check and reserve a wallet rescan */
    1323             : class WalletRescanReserver
    1324             : {
    1325             : private:
    1326             :     CWalletRef m_wallet;
    1327             :     bool m_could_reserve;
    1328             : public:
    1329        1203 :     explicit WalletRescanReserver(CWalletRef w) : m_wallet(w), m_could_reserve(false) {}
    1330             : 
    1331        1193 :     bool reserve()
    1332             :     {
    1333        1193 :         assert(!m_could_reserve);
    1334        1193 :         std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
    1335        1193 :         if (m_wallet->fScanningWallet) {
    1336             :             return false;
    1337             :         }
    1338        1193 :         m_wallet->fScanningWallet = true;
    1339        1193 :         m_could_reserve = true;
    1340        1193 :         return true;
    1341             :     }
    1342             : 
    1343        1179 :     bool isReserved() const
    1344             :     {
    1345        1179 :         return (m_could_reserve && m_wallet->fScanningWallet);
    1346             :     }
    1347             : 
    1348        1203 :     ~WalletRescanReserver()
    1349        1203 :     {
    1350        1203 :         std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
    1351        1203 :         if (m_could_reserve) {
    1352        1203 :             m_wallet->fScanningWallet = false;
    1353             :         }
    1354        1203 :     }
    1355             : };
    1356             : 
    1357             : #endif // PIVX_WALLET_WALLET_H

Generated by: LCOV version 1.14