1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
6 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
11 #include "consensus/consensus.h"
14 #include "primitives/block.h"
15 #include "primitives/transaction.h"
16 #include "tinyformat.h"
17 #include "ui_interface.h"
18 #include "utilstrencodings.h"
19 #include "validationinterface.h"
20 #include "wallet/crypter.h"
21 #include "wallet/wallet_ismine.h"
22 #include "wallet/walletdb.h"
23 #include "zcash/Address.hpp"
38 extern CFeeRate payTxFee;
39 extern CAmount maxTxFee;
40 extern unsigned int nTxConfirmTarget;
41 extern bool bSpendZeroConfChange;
42 extern bool fSendFreeTransactions;
43 extern bool fPayAtLeastCustomFee;
46 static const CAmount DEFAULT_TRANSACTION_FEE = 0;
47 //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
48 static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
50 static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN;
51 //! -txconfirmtarget default
52 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2;
53 //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
54 static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
55 //! Largest (in bytes) free transaction we're willing to create
56 static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
57 //! Size of witness cache
58 // Should be large enough that we can expect not to reorg beyond our cache
59 // unless there is some exceptional network disruption.
60 static const unsigned int WITNESS_CACHE_SIZE = COINBASE_MATURITY;
62 class CAccountingEntry;
71 /** (client) version numbers for particular wallet features */
74 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
76 FEATURE_WALLETCRYPT = 40000, // wallet encryption
77 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
79 FEATURE_LATEST = 60000
83 /** A key pool entry */
91 CKeyPool(const CPubKey& vchPubKeyIn);
93 ADD_SERIALIZE_METHODS;
95 template <typename Stream, typename Operation>
96 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
97 if (!(nType & SER_GETHASH))
100 READWRITE(vchPubKey);
104 /** Address book data */
105 class CAddressBookData
116 typedef std::map<std::string, std::string> StringMap;
122 CScript scriptPubKey;
124 bool fSubtractFeeFromAmount;
127 typedef std::map<std::string, std::string> mapValue_t;
130 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
132 if (!mapValue.count("n"))
134 nOrderPos = -1; // TODO: calculate elsewhere
137 nOrderPos = atoi64(mapValue["n"].c_str());
141 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
145 mapValue["n"] = i64tostr(nOrderPos);
150 CTxDestination destination;
155 /** An note outpoint */
161 // Index into CTransaction.vjoinsplit
163 // Index into JSDescription fields of length ZC_NUM_JS_OUTPUTS
166 JSOutPoint() { SetNull(); }
167 JSOutPoint(uint256 h, size_t js, uint8_t n) : hash {h}, js {js}, n {n} { }
169 ADD_SERIALIZE_METHODS;
171 template <typename Stream, typename Operation>
172 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
178 void SetNull() { hash.SetNull(); }
179 bool IsNull() const { return hash.IsNull(); }
181 friend bool operator<(const JSOutPoint& a, const JSOutPoint& b) {
182 return (a.hash < b.hash ||
183 (a.hash == b.hash && a.js < b.js) ||
184 (a.hash == b.hash && a.js == b.js && a.n < b.n));
187 friend bool operator==(const JSOutPoint& a, const JSOutPoint& b) {
188 return (a.hash == b.hash && a.js == b.js && a.n == b.n);
191 friend bool operator!=(const JSOutPoint& a, const JSOutPoint& b) {
195 std::string ToString() const;
201 libzcash::PaymentAddress address;
203 // It's okay to cache the nullifier in the wallet, because we are storing
204 // the spending key there too, which could be used to derive this.
205 // If PR #1210 is merged, we need to revisit the threat model and decide
206 // whether it is okay to store this unencrypted while the spending key is
211 * Cached incremental witnesses for spendable Notes.
212 * Beginning of the list is the most recent witness.
214 std::list<ZCIncrementalWitness> witnesses;
216 CNoteData() : address(), nullifier() { }
217 CNoteData(libzcash::PaymentAddress a, uint256 n) : address {a}, nullifier {n} { }
219 ADD_SERIALIZE_METHODS;
221 template <typename Stream, typename Operation>
222 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
224 READWRITE(nullifier);
225 READWRITE(witnesses);
228 friend bool operator<(const CNoteData& a, const CNoteData& b) {
229 return (a.address < b.address ||
230 (a.address == b.address && a.nullifier < b.nullifier));
233 friend bool operator==(const CNoteData& a, const CNoteData& b) {
234 return (a.address == b.address && a.nullifier == b.nullifier);
237 friend bool operator!=(const CNoteData& a, const CNoteData& b) {
242 typedef std::map<JSOutPoint, CNoteData> mapNoteData_t;
245 struct CNotePlaintextEntry
248 libzcash::NotePlaintext plaintext;
253 /** A transaction with a merkle branch linking it to the block chain. */
254 class CMerkleTx : public CTransaction
257 int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
261 std::vector<uint256> vMerkleBranch;
265 mutable bool fMerkleVerified;
273 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
280 hashBlock = uint256();
282 fMerkleVerified = false;
285 ADD_SERIALIZE_METHODS;
287 template <typename Stream, typename Operation>
288 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
289 READWRITE(*(CTransaction*)this);
290 nVersion = this->nVersion;
291 READWRITE(hashBlock);
292 READWRITE(vMerkleBranch);
296 int SetMerkleBranch(const CBlock& block);
300 * Return depth of transaction in blockchain:
301 * -1 : not in blockchain, and not in memory pool (conflicted transaction)
302 * 0 : in memory pool, waiting to be included in a block
303 * >=1 : this many blocks deep in the main chain
305 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
306 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
307 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
308 int GetBlocksToMaturity() const;
309 bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
313 * A transaction with a bunch of additional info that only the owner cares about.
314 * It includes any unrecorded transactions needed to link it back to the block chain.
316 class CWalletTx : public CMerkleTx
319 const CWallet* pwallet;
323 mapNoteData_t mapNoteData;
324 std::vector<std::pair<std::string, std::string> > vOrderForm;
325 unsigned int fTimeReceivedIsTxTime;
326 unsigned int nTimeReceived; //! time received by this node
327 unsigned int nTimeSmart;
329 std::string strFromAccount;
330 int64_t nOrderPos; //! position in ordered transaction list
333 mutable bool fDebitCached;
334 mutable bool fCreditCached;
335 mutable bool fImmatureCreditCached;
336 mutable bool fAvailableCreditCached;
337 mutable bool fWatchDebitCached;
338 mutable bool fWatchCreditCached;
339 mutable bool fImmatureWatchCreditCached;
340 mutable bool fAvailableWatchCreditCached;
341 mutable bool fChangeCached;
342 mutable CAmount nDebitCached;
343 mutable CAmount nCreditCached;
344 mutable CAmount nImmatureCreditCached;
345 mutable CAmount nAvailableCreditCached;
346 mutable CAmount nWatchDebitCached;
347 mutable CAmount nWatchCreditCached;
348 mutable CAmount nImmatureWatchCreditCached;
349 mutable CAmount nAvailableWatchCreditCached;
350 mutable CAmount nChangeCached;
357 CWalletTx(const CWallet* pwalletIn)
362 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
367 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
372 void Init(const CWallet* pwalletIn)
378 fTimeReceivedIsTxTime = false;
382 strFromAccount.clear();
383 fDebitCached = false;
384 fCreditCached = false;
385 fImmatureCreditCached = false;
386 fAvailableCreditCached = false;
387 fWatchDebitCached = false;
388 fWatchCreditCached = false;
389 fImmatureWatchCreditCached = false;
390 fAvailableWatchCreditCached = false;
391 fChangeCached = false;
394 nImmatureCreditCached = 0;
395 nAvailableCreditCached = 0;
396 nWatchDebitCached = 0;
397 nWatchCreditCached = 0;
398 nAvailableWatchCreditCached = 0;
399 nImmatureWatchCreditCached = 0;
404 ADD_SERIALIZE_METHODS;
406 template <typename Stream, typename Operation>
407 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
408 if (ser_action.ForRead())
412 if (!ser_action.ForRead())
414 mapValue["fromaccount"] = strFromAccount;
416 WriteOrderPos(nOrderPos, mapValue);
419 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
422 READWRITE(*(CMerkleTx*)this);
423 std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
426 READWRITE(mapNoteData);
427 READWRITE(vOrderForm);
428 READWRITE(fTimeReceivedIsTxTime);
429 READWRITE(nTimeReceived);
433 if (ser_action.ForRead())
435 strFromAccount = mapValue["fromaccount"];
437 ReadOrderPos(nOrderPos, mapValue);
439 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
442 mapValue.erase("fromaccount");
443 mapValue.erase("version");
444 mapValue.erase("spent");
446 mapValue.erase("timesmart");
449 //! make sure balances are recalculated
452 fCreditCached = false;
453 fAvailableCreditCached = false;
454 fWatchDebitCached = false;
455 fWatchCreditCached = false;
456 fAvailableWatchCreditCached = false;
457 fImmatureWatchCreditCached = false;
458 fDebitCached = false;
459 fChangeCached = false;
462 void BindWallet(CWallet *pwalletIn)
468 void SetNoteData(mapNoteData_t ¬eData);
470 //! filter decides which addresses will count towards the debit
471 CAmount GetDebit(const isminefilter& filter) const;
472 CAmount GetCredit(const isminefilter& filter) const;
473 CAmount GetImmatureCredit(bool fUseCache=true) const;
474 CAmount GetAvailableCredit(bool fUseCache=true) const;
475 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
476 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
477 CAmount GetChange() const;
479 void GetAmounts(std::list<COutputEntry>& listReceived,
480 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
482 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
483 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
485 bool IsFromMe(const isminefilter& filter) const
487 return (GetDebit(filter) > 0);
490 bool IsTrusted() const;
492 bool WriteToDisk(CWalletDB *pwalletdb);
494 int64_t GetTxTime() const;
495 int GetRequestCount() const;
497 bool RelayWalletTransaction();
499 std::set<uint256> GetConflicts() const;
513 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
515 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
518 std::string ToString() const;
524 /** Private key that includes an expiration date in case it never gets used. */
529 int64_t nTimeCreated;
530 int64_t nTimeExpires;
531 std::string strComment;
532 //! todo: add something to note what created it (user, getnewaddress, change)
533 //! maybe should have a map<string, string> property map
535 CWalletKey(int64_t nExpires=0);
537 ADD_SERIALIZE_METHODS;
539 template <typename Stream, typename Operation>
540 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
541 if (!(nType & SER_GETHASH))
543 READWRITE(vchPrivKey);
544 READWRITE(nTimeCreated);
545 READWRITE(nTimeExpires);
546 READWRITE(LIMITED_STRING(strComment, 65536));
553 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
554 * and provides the ability to create new transactions.
556 class CWallet : public CCryptoKeyStore, public CValidationInterface
559 bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
561 CWalletDB *pwalletdbEncryption;
563 //! the current wallet version: clients below this version are not able to load the wallet
566 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
567 int nWalletMaxVersion;
571 bool fBroadcastTransactions;
574 using TxSpendMap = std::multimap<T, uint256>;
576 * Used to keep track of spent outpoints, and
577 * detect and report conflicts (double-spends or
578 * mutated transactions where the mutant gets mined).
580 typedef TxSpendMap<COutPoint> TxSpends;
581 TxSpends mapTxSpends;
583 * Used to keep track of spent Notes, and
584 * detect and report conflicts (double-spends).
586 typedef TxSpendMap<uint256> TxNullifiers;
587 TxNullifiers mapTxNullifiers;
589 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
590 void AddToSpends(const uint256& nullifier, const uint256& wtxid);
591 void AddToSpends(const uint256& wtxid);
595 * Size of the incremental witness cache for the notes in our wallet.
596 * This will always be greater than or equal to the size of the largest
597 * incremental witness cache in any transaction in mapWallet.
599 int64_t nWitnessCacheSize;
601 void ClearNoteWitnessCache();
604 void IncrementNoteWitnesses(const CBlockIndex* pindex,
605 const CBlock* pblock,
606 ZCIncrementalMerkleTree tree);
607 void DecrementNoteWitnesses();
608 void WriteWitnessCache();
612 void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
615 bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
616 void MarkAffectedTransactionsDirty(const CTransaction& tx);
621 * This lock protects all the fields added by CWallet
623 * fFileBacked (immutable after instantiation)
624 * strWalletFile (immutable after instantiation)
626 mutable CCriticalSection cs_wallet;
629 std::string strWalletFile;
631 std::set<int64_t> setKeyPool;
632 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
633 std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
635 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
636 MasterKeyMap mapMasterKeys;
637 unsigned int nMasterKeyMaxID;
644 CWallet(std::string strWalletFileIn)
648 strWalletFile = strWalletFileIn;
654 delete pwalletdbEncryption;
655 pwalletdbEncryption = NULL;
660 nWalletVersion = FEATURE_BASE;
661 nWalletMaxVersion = FEATURE_BASE;
664 pwalletdbEncryption = NULL;
669 fBroadcastTransactions = false;
670 nWitnessCacheSize = 0;
673 std::map<uint256, JSOutPoint> mapNullifiersToNotes;
674 std::map<uint256, CWalletTx> mapWallet;
676 int64_t nOrderPosNext;
677 std::map<uint256, int> mapRequestCount;
679 std::map<CTxDestination, CAddressBookData> mapAddressBook;
681 CPubKey vchDefaultKey;
683 std::set<COutPoint> setLockedCoins;
685 int64_t nTimeFirstKey;
687 const CWalletTx* GetWalletTx(const uint256& hash) const;
689 //! check whether we are allowed to upgrade (or already support) to the named feature
690 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
692 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false) const;
693 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const;
695 bool IsSpent(const uint256& hash, unsigned int n) const;
696 bool IsSpent(const uint256& nullifier) const;
698 bool IsLockedCoin(uint256 hash, unsigned int n) const;
699 void LockCoin(COutPoint& output);
700 void UnlockCoin(COutPoint& output);
701 void UnlockAllCoins();
702 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
705 * keystore implementation
708 CPubKey GenerateNewKey();
709 //! Adds a key to the store, and saves it to disk.
710 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
711 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
712 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
713 //! Load metadata (used by LoadWallet)
714 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
716 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
718 //! Adds an encrypted key to the store, and saves it to disk.
719 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
720 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
721 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
722 bool AddCScript(const CScript& redeemScript);
723 bool LoadCScript(const CScript& redeemScript);
725 //! Adds a destination data tuple to the store, and saves it to disk
726 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
727 //! Erases a destination data tuple in the store and on disk
728 bool EraseDestData(const CTxDestination &dest, const std::string &key);
729 //! Adds a destination data tuple to the store, without saving it to disk
730 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
731 //! Look up a destination data tuple in the store, return true if found false otherwise
732 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
734 //! Adds a watch-only address to the store, and saves it to disk.
735 bool AddWatchOnly(const CScript &dest);
736 bool RemoveWatchOnly(const CScript &dest);
737 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
738 bool LoadWatchOnly(const CScript &dest);
740 bool Unlock(const SecureString& strWalletPassphrase);
741 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
742 bool EncryptWallet(const SecureString& strWalletPassphrase);
744 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
749 //! Generates a new zaddr
750 CZCPaymentAddress GenerateNewZKey();
751 //! Adds spending key to the store, and saves it to disk
752 bool AddZKey(const libzcash::SpendingKey &key);
753 //! Adds spending key to the store, without saving it to disk (used by LoadWallet)
754 bool LoadZKey(const libzcash::SpendingKey &key);
755 //! Load spending key metadata (used by LoadWallet)
756 bool LoadZKeyMetadata(const libzcash::PaymentAddress &addr, const CKeyMetadata &meta);
757 //! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
758 bool LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ViewingKey &vk, const std::vector<unsigned char> &vchCryptedSecret);
759 //! Adds an encrypted spending key to the store, and saves it to disk (virtual method, declared in crypter.h)
760 bool AddCryptedSpendingKey(const libzcash::PaymentAddress &address, const libzcash::ViewingKey &vk, const std::vector<unsigned char> &vchCryptedSecret);
763 * Increment the next transaction order id
764 * @return next transaction order id
766 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
768 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
769 typedef std::multimap<int64_t, TxPair > TxItems;
772 * Get the wallet's activity log
773 * @return multimap of ordered transactions and accounting entries
774 * @warning Returned pointers are *only* valid within the scope of passed acentries
776 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
779 void UpdateNullifierNoteMap(const CWalletTx& wtx);
780 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
781 void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
782 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
783 void EraseFromWallet(const uint256 &hash);
784 void WitnessNoteCommitment(
785 std::vector<uint256> commitments,
786 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
787 uint256 &final_anchor);
788 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
789 void ReacceptWalletTransactions();
790 void ResendWalletTransactions(int64_t nBestBlockTime);
791 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
792 CAmount GetBalance() const;
793 CAmount GetUnconfirmedBalance() const;
794 CAmount GetImmatureBalance() const;
795 CAmount GetWatchOnlyBalance() const;
796 CAmount GetUnconfirmedWatchOnlyBalance() const;
797 CAmount GetImmatureWatchOnlyBalance() const;
798 bool CreateTransaction(const std::vector<CRecipient>& vecSend,
799 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
800 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
802 static CFeeRate minTxFee;
803 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
806 bool TopUpKeyPool(unsigned int kpSize = 0);
807 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
808 void KeepKey(int64_t nIndex);
809 void ReturnKey(int64_t nIndex);
810 bool GetKeyFromPool(CPubKey &key);
811 int64_t GetOldestKeyPoolTime();
812 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
814 std::set< std::set<CTxDestination> > GetAddressGroupings();
815 std::map<CTxDestination, CAmount> GetAddressBalances();
817 std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
819 mapNoteData_t FindMyNotes(const CTransaction& tx) const;
820 bool IsFromMe(const uint256& nullifier) const;
821 void GetNoteWitnesses(
822 std::vector<JSOutPoint> notes,
823 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
824 uint256 &final_anchor);
826 isminetype IsMine(const CTxIn& txin) const;
827 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
828 isminetype IsMine(const CTxOut& txout) const;
829 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
830 bool IsChange(const CTxOut& txout) const;
831 CAmount GetChange(const CTxOut& txout) const;
832 bool IsMine(const CTransaction& tx) const;
833 /** should probably be renamed to IsRelevantToMe */
834 bool IsFromMe(const CTransaction& tx) const;
835 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
836 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
837 CAmount GetChange(const CTransaction& tx) const;
838 void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, ZCIncrementalMerkleTree tree, bool added);
839 void SetBestChain(const CBlockLocator& loc);
841 DBErrors LoadWallet(bool& fFirstRunRet);
842 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
844 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
846 bool DelAddressBook(const CTxDestination& address);
848 void UpdatedTransaction(const uint256 &hashTx);
850 void Inventory(const uint256 &hash)
854 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
855 if (mi != mapRequestCount.end())
860 unsigned int GetKeyPoolSize()
862 AssertLockHeld(cs_wallet); // setKeyPool
863 return setKeyPool.size();
866 bool SetDefaultKey(const CPubKey &vchPubKey);
868 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
869 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
871 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
872 bool SetMaxVersion(int nVersion);
874 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
875 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
877 //! Get wallet transactions that conflict with given transaction (spend same outputs)
878 std::set<uint256> GetConflicts(const uint256& txid) const;
880 //! Flush wallet (bitdb flush)
881 void Flush(bool shutdown=false);
883 //! Verify the wallet database and perform salvage if required
884 static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
887 * Address book entry changed.
888 * @note called with lock cs_wallet held.
890 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
891 &address, const std::string &label, bool isMine,
892 const std::string &purpose,
893 ChangeType status)> NotifyAddressBookChanged;
896 * Wallet transaction added, removed or updated.
897 * @note called with lock cs_wallet held.
899 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
900 ChangeType status)> NotifyTransactionChanged;
902 /** Show progress e.g. for rescan */
903 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
905 /** Watch-only address added */
906 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
908 /** Inquire whether this wallet broadcasts transactions. */
909 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
910 /** Set whether this wallet broadcasts transactions. */
911 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
913 /* Find notes filtered by payment address, min depth, ability to spend */
914 bool GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth=1, bool ignoreSpent=true);
918 /** A key allocated from the key pool. */
926 CReserveKey(CWallet* pwalletIn)
938 bool GetReservedKey(CPubKey &pubkey);
944 * Account information.
945 * Stored in wallet with key "acc"+string account name.
959 vchPubKey = CPubKey();
962 ADD_SERIALIZE_METHODS;
964 template <typename Stream, typename Operation>
965 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
966 if (!(nType & SER_GETHASH))
968 READWRITE(vchPubKey);
975 * Internal transfers.
976 * Database key is acentry<account><counter>.
978 class CAccountingEntry
981 std::string strAccount;
982 CAmount nCreditDebit;
984 std::string strOtherAccount;
985 std::string strComment;
987 int64_t nOrderPos; //! position in ordered transaction list
1000 strOtherAccount.clear();
1006 ADD_SERIALIZE_METHODS;
1008 template <typename Stream, typename Operation>
1009 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1010 if (!(nType & SER_GETHASH))
1011 READWRITE(nVersion);
1012 //! Note: strAccount is serialized as part of the key, not here.
1013 READWRITE(nCreditDebit);
1015 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
1017 if (!ser_action.ForRead())
1019 WriteOrderPos(nOrderPos, mapValue);
1021 if (!(mapValue.empty() && _ssExtra.empty()))
1023 CDataStream ss(nType, nVersion);
1024 ss.insert(ss.begin(), '\0');
1026 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1027 strComment.append(ss.str());
1031 READWRITE(LIMITED_STRING(strComment, 65536));
1033 size_t nSepPos = strComment.find("\0", 0, 1);
1034 if (ser_action.ForRead())
1037 if (std::string::npos != nSepPos)
1039 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1041 _ssExtra = std::vector<char>(ss.begin(), ss.end());
1043 ReadOrderPos(nOrderPos, mapValue);
1045 if (std::string::npos != nSepPos)
1046 strComment.erase(nSepPos);
1048 mapValue.erase("n");
1052 std::vector<char> _ssExtra;
1055 #endif // BITCOIN_WALLET_WALLET_H