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"
19 #include "utilstrencodings.h"
20 #include "validationinterface.h"
21 #include "wallet/crypter.h"
22 #include "wallet/wallet_ismine.h"
23 #include "wallet/walletdb.h"
24 #include "zcash/Address.hpp"
39 extern CFeeRate payTxFee;
40 extern CAmount maxTxFee;
41 extern unsigned int nTxConfirmTarget;
42 extern bool bSpendZeroConfChange;
43 extern bool fSendFreeTransactions;
44 extern bool fPayAtLeastCustomFee;
47 static const CAmount DEFAULT_TRANSACTION_FEE = 0;
48 //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
49 static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
51 static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN;
52 //! -txconfirmtarget default
53 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2;
54 //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
55 static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
56 //! Largest (in bytes) free transaction we're willing to create
57 static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
58 //! Size of witness cache
59 // Should be large enough that we can expect not to reorg beyond our cache
60 // unless there is some exceptional network disruption.
61 static const unsigned int WITNESS_CACHE_SIZE = COINBASE_MATURITY;
63 class CAccountingEntry;
72 /** (client) version numbers for particular wallet features */
75 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
77 FEATURE_WALLETCRYPT = 40000, // wallet encryption
78 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
80 FEATURE_LATEST = 60000
84 /** A key pool entry */
92 CKeyPool(const CPubKey& vchPubKeyIn);
94 ADD_SERIALIZE_METHODS;
96 template <typename Stream, typename Operation>
97 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
98 if (!(nType & SER_GETHASH))
101 READWRITE(vchPubKey);
105 /** Address book data */
106 class CAddressBookData
117 typedef std::map<std::string, std::string> StringMap;
123 CScript scriptPubKey;
125 bool fSubtractFeeFromAmount;
128 typedef std::map<std::string, std::string> mapValue_t;
131 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
133 if (!mapValue.count("n"))
135 nOrderPos = -1; // TODO: calculate elsewhere
138 nOrderPos = atoi64(mapValue["n"].c_str());
142 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
146 mapValue["n"] = i64tostr(nOrderPos);
151 CTxDestination destination;
156 /** An note outpoint */
162 // Index into CTransaction.vjoinsplit
164 // Index into JSDescription fields of length ZC_NUM_JS_OUTPUTS
167 JSOutPoint() { SetNull(); }
168 JSOutPoint(uint256 h, size_t js, uint8_t n) : hash {h}, js {js}, n {n} { }
170 ADD_SERIALIZE_METHODS;
172 template <typename Stream, typename Operation>
173 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
179 void SetNull() { hash.SetNull(); }
180 bool IsNull() const { return hash.IsNull(); }
182 friend bool operator<(const JSOutPoint& a, const JSOutPoint& b) {
183 return (a.hash < b.hash ||
184 (a.hash == b.hash && a.js < b.js) ||
185 (a.hash == b.hash && a.js == b.js && a.n < b.n));
188 friend bool operator==(const JSOutPoint& a, const JSOutPoint& b) {
189 return (a.hash == b.hash && a.js == b.js && a.n == b.n);
192 friend bool operator!=(const JSOutPoint& a, const JSOutPoint& b) {
196 std::string ToString() const;
202 libzcash::PaymentAddress address;
205 * Cached note nullifier. May not be set if the wallet was not unlocked when
206 * this was CNoteData was created. If not set, we always assume that the
207 * note has not been spent.
209 * It's okay to cache the nullifier in the wallet, because we are storing
210 * the spending key there too, which could be used to derive this.
211 * If the wallet is encrypted, this means that someone with access to the
212 * locked wallet cannot spend notes, but can connect received notes to the
213 * transactions they are spent in. This is the same security semantics as
214 * for transparent addresses.
216 boost::optional<uint256> nullifier;
219 * Cached incremental witnesses for spendable Notes.
220 * Beginning of the list is the most recent witness.
222 std::list<ZCIncrementalWitness> witnesses;
225 * Block height corresponding to the most current witness.
227 * When we first create a CNoteData in CWallet::FindMyNotes, this is set to
228 * -1 as a placeholder. The next time CWallet::ChainTip is called, we can
229 * determine what height the witness cache for this note is valid for (even
230 * if no witnesses were cached), and so can set the correct value in
231 * CWallet::IncrementNoteWitnesses and CWallet::DecrementNoteWitnesses.
235 CNoteData() : address(), nullifier(), witnessHeight {-1} { }
236 CNoteData(libzcash::PaymentAddress a) :
237 address {a}, nullifier(), witnessHeight {-1} { }
238 CNoteData(libzcash::PaymentAddress a, uint256 n) :
239 address {a}, nullifier {n}, witnessHeight {-1} { }
241 ADD_SERIALIZE_METHODS;
243 template <typename Stream, typename Operation>
244 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
246 READWRITE(nullifier);
247 READWRITE(witnesses);
248 READWRITE(witnessHeight);
251 friend bool operator<(const CNoteData& a, const CNoteData& b) {
252 return (a.address < b.address ||
253 (a.address == b.address && a.nullifier < b.nullifier));
256 friend bool operator==(const CNoteData& a, const CNoteData& b) {
257 return (a.address == b.address && a.nullifier == b.nullifier);
260 friend bool operator!=(const CNoteData& a, const CNoteData& b) {
265 typedef std::map<JSOutPoint, CNoteData> mapNoteData_t;
267 /** Decrypted note and its location in a transaction. */
268 struct CNotePlaintextEntry
271 libzcash::NotePlaintext plaintext;
276 /** A transaction with a merkle branch linking it to the block chain. */
277 class CMerkleTx : public CTransaction
280 int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
284 std::vector<uint256> vMerkleBranch;
288 mutable bool fMerkleVerified;
296 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
303 hashBlock = uint256();
305 fMerkleVerified = false;
308 ADD_SERIALIZE_METHODS;
310 template <typename Stream, typename Operation>
311 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
312 READWRITE(*(CTransaction*)this);
313 nVersion = this->nVersion;
314 READWRITE(hashBlock);
315 READWRITE(vMerkleBranch);
319 int SetMerkleBranch(const CBlock& block);
323 * Return depth of transaction in blockchain:
324 * -1 : not in blockchain, and not in memory pool (conflicted transaction)
325 * 0 : in memory pool, waiting to be included in a block
326 * >=1 : this many blocks deep in the main chain
328 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
329 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
330 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
331 int GetBlocksToMaturity() const;
332 bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
336 * A transaction with a bunch of additional info that only the owner cares about.
337 * It includes any unrecorded transactions needed to link it back to the block chain.
339 class CWalletTx : public CMerkleTx
342 const CWallet* pwallet;
346 mapNoteData_t mapNoteData;
347 std::vector<std::pair<std::string, std::string> > vOrderForm;
348 unsigned int fTimeReceivedIsTxTime;
349 unsigned int nTimeReceived; //! time received by this node
350 unsigned int nTimeSmart;
352 std::string strFromAccount;
353 int64_t nOrderPos; //! position in ordered transaction list
356 mutable bool fDebitCached;
357 mutable bool fCreditCached;
358 mutable bool fImmatureCreditCached;
359 mutable bool fAvailableCreditCached;
360 mutable bool fWatchDebitCached;
361 mutable bool fWatchCreditCached;
362 mutable bool fImmatureWatchCreditCached;
363 mutable bool fAvailableWatchCreditCached;
364 mutable bool fChangeCached;
365 mutable CAmount nDebitCached;
366 mutable CAmount nCreditCached;
367 mutable CAmount nImmatureCreditCached;
368 mutable CAmount nAvailableCreditCached;
369 mutable CAmount nWatchDebitCached;
370 mutable CAmount nWatchCreditCached;
371 mutable CAmount nImmatureWatchCreditCached;
372 mutable CAmount nAvailableWatchCreditCached;
373 mutable CAmount nChangeCached;
380 CWalletTx(const CWallet* pwalletIn)
385 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
390 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
395 void Init(const CWallet* pwalletIn)
401 fTimeReceivedIsTxTime = false;
405 strFromAccount.clear();
406 fDebitCached = false;
407 fCreditCached = false;
408 fImmatureCreditCached = false;
409 fAvailableCreditCached = false;
410 fWatchDebitCached = false;
411 fWatchCreditCached = false;
412 fImmatureWatchCreditCached = false;
413 fAvailableWatchCreditCached = false;
414 fChangeCached = false;
417 nImmatureCreditCached = 0;
418 nAvailableCreditCached = 0;
419 nWatchDebitCached = 0;
420 nWatchCreditCached = 0;
421 nAvailableWatchCreditCached = 0;
422 nImmatureWatchCreditCached = 0;
427 ADD_SERIALIZE_METHODS;
429 template <typename Stream, typename Operation>
430 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
431 if (ser_action.ForRead())
435 if (!ser_action.ForRead())
437 mapValue["fromaccount"] = strFromAccount;
439 WriteOrderPos(nOrderPos, mapValue);
442 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
445 READWRITE(*(CMerkleTx*)this);
446 std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
449 READWRITE(mapNoteData);
450 READWRITE(vOrderForm);
451 READWRITE(fTimeReceivedIsTxTime);
452 READWRITE(nTimeReceived);
456 if (ser_action.ForRead())
458 strFromAccount = mapValue["fromaccount"];
460 ReadOrderPos(nOrderPos, mapValue);
462 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
465 mapValue.erase("fromaccount");
466 mapValue.erase("version");
467 mapValue.erase("spent");
469 mapValue.erase("timesmart");
472 //! make sure balances are recalculated
475 fCreditCached = false;
476 fAvailableCreditCached = false;
477 fWatchDebitCached = false;
478 fWatchCreditCached = false;
479 fAvailableWatchCreditCached = false;
480 fImmatureWatchCreditCached = false;
481 fDebitCached = false;
482 fChangeCached = false;
485 void BindWallet(CWallet *pwalletIn)
491 void SetNoteData(mapNoteData_t ¬eData);
493 //! filter decides which addresses will count towards the debit
494 CAmount GetDebit(const isminefilter& filter) const;
495 CAmount GetCredit(const isminefilter& filter) const;
496 CAmount GetImmatureCredit(bool fUseCache=true) const;
497 CAmount GetAvailableCredit(bool fUseCache=true) const;
498 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
499 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
500 CAmount GetChange() const;
502 void GetAmounts(std::list<COutputEntry>& listReceived,
503 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
505 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
506 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
508 bool IsFromMe(const isminefilter& filter) const
510 return (GetDebit(filter) > 0);
513 bool IsTrusted() const;
515 bool WriteToDisk(CWalletDB *pwalletdb);
517 int64_t GetTxTime() const;
518 int GetRequestCount() const;
520 bool RelayWalletTransaction();
522 std::set<uint256> GetConflicts() const;
536 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
538 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
541 std::string ToString() const;
547 /** Private key that includes an expiration date in case it never gets used. */
552 int64_t nTimeCreated;
553 int64_t nTimeExpires;
554 std::string strComment;
555 //! todo: add something to note what created it (user, getnewaddress, change)
556 //! maybe should have a map<string, string> property map
558 CWalletKey(int64_t nExpires=0);
560 ADD_SERIALIZE_METHODS;
562 template <typename Stream, typename Operation>
563 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
564 if (!(nType & SER_GETHASH))
566 READWRITE(vchPrivKey);
567 READWRITE(nTimeCreated);
568 READWRITE(nTimeExpires);
569 READWRITE(LIMITED_STRING(strComment, 65536));
576 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
577 * and provides the ability to create new transactions.
579 class CWallet : public CCryptoKeyStore, public CValidationInterface
582 bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl *coinControl = NULL) const;
584 CWalletDB *pwalletdbEncryption;
586 //! the current wallet version: clients below this version are not able to load the wallet
589 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
590 int nWalletMaxVersion;
594 bool fBroadcastTransactions;
597 using TxSpendMap = std::multimap<T, uint256>;
599 * Used to keep track of spent outpoints, and
600 * detect and report conflicts (double-spends or
601 * mutated transactions where the mutant gets mined).
603 typedef TxSpendMap<COutPoint> TxSpends;
604 TxSpends mapTxSpends;
606 * Used to keep track of spent Notes, and
607 * detect and report conflicts (double-spends).
609 typedef TxSpendMap<uint256> TxNullifiers;
610 TxNullifiers mapTxNullifiers;
612 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
613 void AddToSpends(const uint256& nullifier, const uint256& wtxid);
614 void AddToSpends(const uint256& wtxid);
618 * Size of the incremental witness cache for the notes in our wallet.
619 * This will always be greater than or equal to the size of the largest
620 * incremental witness cache in any transaction in mapWallet.
622 int64_t nWitnessCacheSize;
624 void ClearNoteWitnessCache();
628 * pindex is the new tip being connected.
630 void IncrementNoteWitnesses(const CBlockIndex* pindex,
631 const CBlock* pblock,
632 ZCIncrementalMerkleTree& tree);
634 * pindex is the old tip being disconnected.
636 void DecrementNoteWitnesses(const CBlockIndex* pindex);
638 template <typename WalletDB>
639 void SetBestChainINTERNAL(WalletDB& walletdb, const CBlockLocator& loc) {
640 if (!walletdb.TxnBegin()) {
641 // This needs to be done atomically, so don't do it at all
642 LogPrintf("SetBestChain(): Couldn't start atomic write\n");
646 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
647 if (!walletdb.WriteTx(wtxItem.first, wtxItem.second)) {
648 LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
653 if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
654 LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
658 if (!walletdb.WriteBestBlock(loc)) {
659 LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
663 } catch (const std::exception &exc) {
664 // Unexpected failure
665 LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
666 LogPrintf("%s\n", exc.what());
670 if (!walletdb.TxnCommit()) {
671 // Couldn't commit all to db, but in-memory state is fine
672 LogPrintf("SetBestChain(): Couldn't commit atomic write\n");
679 void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
682 bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
683 void MarkAffectedTransactionsDirty(const CTransaction& tx);
688 * This lock protects all the fields added by CWallet
690 * fFileBacked (immutable after instantiation)
691 * strWalletFile (immutable after instantiation)
693 mutable CCriticalSection cs_wallet;
696 std::string strWalletFile;
698 std::set<int64_t> setKeyPool;
699 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
700 std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
702 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
703 MasterKeyMap mapMasterKeys;
704 unsigned int nMasterKeyMaxID;
711 CWallet(const std::string& strWalletFileIn)
715 strWalletFile = strWalletFileIn;
721 delete pwalletdbEncryption;
722 pwalletdbEncryption = NULL;
727 nWalletVersion = FEATURE_BASE;
728 nWalletMaxVersion = FEATURE_BASE;
731 pwalletdbEncryption = NULL;
736 fBroadcastTransactions = false;
737 nWitnessCacheSize = 0;
741 * The reverse mapping of nullifiers to notes.
743 * The mapping cannot be updated while an encrypted wallet is locked,
744 * because we need the SpendingKey to create the nullifier (#1502). This has
745 * several implications for transactions added to the wallet while locked:
747 * - Parent transactions can't be marked dirty when a child transaction that
748 * spends their output notes is updated.
750 * - We currently don't cache any note values, so this is not a problem,
753 * - GetFilteredNotes can't filter out spent notes.
755 * - Per the comment in CNoteData, we assume that if we don't have a
756 * cached nullifier, the note is not spent.
758 * Another more problematic implication is that the wallet can fail to
759 * detect transactions on the blockchain that spend our notes. There are two
760 * possible cases in which this could happen:
762 * - We receive a note when the wallet is locked, and then spend it using a
763 * different wallet client.
765 * - We spend from a PaymentAddress we control, then we export the
766 * SpendingKey and import it into a new wallet, and reindex/rescan to find
767 * the old transactions.
769 * The wallet will only miss "pure" spends - transactions that are only
770 * linked to us by the fact that they contain notes we spent. If it also
771 * sends notes to us, or interacts with our transparent addresses, we will
772 * detect the transaction and add it to the wallet (again without caching
773 * nullifiers for new notes). As by default JoinSplits send change back to
774 * the origin PaymentAddress, the wallet should rarely miss transactions.
776 * To work around these issues, whenever the wallet is unlocked, we scan all
777 * cached notes, and cache any missing nullifiers. Since the wallet must be
778 * unlocked in order to spend notes, this means that GetFilteredNotes will
779 * always behave correctly within that context (and any other uses will give
780 * correct responses afterwards), for the transactions that the wallet was
781 * able to detect. Any missing transactions can be rediscovered by:
783 * - Unlocking the wallet (to fill all nullifier caches).
785 * - Restarting the node with -reindex (which operates on a locked wallet
786 * but with the now-cached nullifiers).
788 std::map<uint256, JSOutPoint> mapNullifiersToNotes;
790 std::map<uint256, CWalletTx> mapWallet;
792 int64_t nOrderPosNext;
793 std::map<uint256, int> mapRequestCount;
795 std::map<CTxDestination, CAddressBookData> mapAddressBook;
797 CPubKey vchDefaultKey;
799 std::set<COutPoint> setLockedCoins;
801 int64_t nTimeFirstKey;
803 const CWalletTx* GetWalletTx(const uint256& hash) const;
805 //! check whether we are allowed to upgrade (or already support) to the named feature
806 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
808 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, bool fIncludeCoinBase=true) const;
809 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;
811 bool IsSpent(const uint256& hash, unsigned int n) const;
812 bool IsSpent(const uint256& nullifier) const;
814 bool IsLockedCoin(uint256 hash, unsigned int n) const;
815 void LockCoin(COutPoint& output);
816 void UnlockCoin(COutPoint& output);
817 void UnlockAllCoins();
818 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
821 * keystore implementation
824 CPubKey GenerateNewKey();
825 //! Adds a key to the store, and saves it to disk.
826 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
827 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
828 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
829 //! Load metadata (used by LoadWallet)
830 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
832 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
834 //! Adds an encrypted key to the store, and saves it to disk.
835 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
836 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
837 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
838 bool AddCScript(const CScript& redeemScript);
839 bool LoadCScript(const CScript& redeemScript);
841 //! Adds a destination data tuple to the store, and saves it to disk
842 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
843 //! Erases a destination data tuple in the store and on disk
844 bool EraseDestData(const CTxDestination &dest, const std::string &key);
845 //! Adds a destination data tuple to the store, without saving it to disk
846 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
847 //! Look up a destination data tuple in the store, return true if found false otherwise
848 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
850 //! Adds a watch-only address to the store, and saves it to disk.
851 bool AddWatchOnly(const CScript &dest);
852 bool RemoveWatchOnly(const CScript &dest);
853 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
854 bool LoadWatchOnly(const CScript &dest);
856 bool Unlock(const SecureString& strWalletPassphrase);
857 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
858 bool EncryptWallet(const SecureString& strWalletPassphrase);
860 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
865 //! Generates a new zaddr
866 CZCPaymentAddress GenerateNewZKey();
867 //! Adds spending key to the store, and saves it to disk
868 bool AddZKey(const libzcash::SpendingKey &key);
869 //! Adds spending key to the store, without saving it to disk (used by LoadWallet)
870 bool LoadZKey(const libzcash::SpendingKey &key);
871 //! Load spending key metadata (used by LoadWallet)
872 bool LoadZKeyMetadata(const libzcash::PaymentAddress &addr, const CKeyMetadata &meta);
873 //! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
874 bool LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ViewingKey &vk, const std::vector<unsigned char> &vchCryptedSecret);
875 //! Adds an encrypted spending key to the store, and saves it to disk (virtual method, declared in crypter.h)
876 bool AddCryptedSpendingKey(const libzcash::PaymentAddress &address, const libzcash::ViewingKey &vk, const std::vector<unsigned char> &vchCryptedSecret);
879 * Increment the next transaction order id
880 * @return next transaction order id
882 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
884 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
885 typedef std::multimap<int64_t, TxPair > TxItems;
888 * Get the wallet's activity log
889 * @return multimap of ordered transactions and accounting entries
890 * @warning Returned pointers are *only* valid within the scope of passed acentries
892 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
895 bool UpdateNullifierNoteMap();
896 void UpdateNullifierNoteMapWithTx(const CWalletTx& wtx);
897 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
898 void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
899 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
900 void EraseFromWallet(const uint256 &hash);
901 void WitnessNoteCommitment(
902 std::vector<uint256> commitments,
903 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
904 uint256 &final_anchor);
905 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
906 void ReacceptWalletTransactions();
907 void ResendWalletTransactions(int64_t nBestBlockTime);
908 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
909 CAmount GetBalance() const;
910 CAmount GetUnconfirmedBalance() const;
911 CAmount GetImmatureBalance() const;
912 CAmount GetWatchOnlyBalance() const;
913 CAmount GetUnconfirmedWatchOnlyBalance() const;
914 CAmount GetImmatureWatchOnlyBalance() const;
915 bool CreateTransaction(const std::vector<CRecipient>& vecSend,
916 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
917 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
919 static CFeeRate minTxFee;
920 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
923 bool TopUpKeyPool(unsigned int kpSize = 0);
924 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
925 void KeepKey(int64_t nIndex);
926 void ReturnKey(int64_t nIndex);
927 bool GetKeyFromPool(CPubKey &key);
928 int64_t GetOldestKeyPoolTime();
929 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
931 std::set< std::set<CTxDestination> > GetAddressGroupings();
932 std::map<CTxDestination, CAmount> GetAddressBalances();
934 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
936 boost::optional<uint256> GetNoteNullifier(
937 const JSDescription& jsdesc,
938 const libzcash::PaymentAddress& address,
939 const ZCNoteDecryption& dec,
942 mapNoteData_t FindMyNotes(const CTransaction& tx) const;
943 bool IsFromMe(const uint256& nullifier) const;
944 void GetNoteWitnesses(
945 std::vector<JSOutPoint> notes,
946 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
947 uint256 &final_anchor);
949 isminetype IsMine(const CTxIn& txin) const;
950 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
951 isminetype IsMine(const CTxOut& txout) const;
952 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
953 bool IsChange(const CTxOut& txout) const;
954 CAmount GetChange(const CTxOut& txout) const;
955 bool IsMine(const CTransaction& tx) const;
956 /** should probably be renamed to IsRelevantToMe */
957 bool IsFromMe(const CTransaction& tx) const;
958 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
959 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
960 CAmount GetChange(const CTransaction& tx) const;
961 void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, ZCIncrementalMerkleTree tree, bool added);
962 /** Saves witness caches and best block locator to disk. */
963 void SetBestChain(const CBlockLocator& loc);
965 DBErrors LoadWallet(bool& fFirstRunRet);
966 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
968 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
970 bool DelAddressBook(const CTxDestination& address);
972 void UpdatedTransaction(const uint256 &hashTx);
974 void Inventory(const uint256 &hash)
978 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
979 if (mi != mapRequestCount.end())
984 unsigned int GetKeyPoolSize()
986 AssertLockHeld(cs_wallet); // setKeyPool
987 return setKeyPool.size();
990 bool SetDefaultKey(const CPubKey &vchPubKey);
992 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
993 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
995 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
996 bool SetMaxVersion(int nVersion);
998 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
999 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1001 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1002 std::set<uint256> GetConflicts(const uint256& txid) const;
1004 //! Flush wallet (bitdb flush)
1005 void Flush(bool shutdown=false);
1007 //! Verify the wallet database and perform salvage if required
1008 static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
1011 * Address book entry changed.
1012 * @note called with lock cs_wallet held.
1014 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1015 &address, const std::string &label, bool isMine,
1016 const std::string &purpose,
1017 ChangeType status)> NotifyAddressBookChanged;
1020 * Wallet transaction added, removed or updated.
1021 * @note called with lock cs_wallet held.
1023 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1024 ChangeType status)> NotifyTransactionChanged;
1026 /** Show progress e.g. for rescan */
1027 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1029 /** Watch-only address added */
1030 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1032 /** Inquire whether this wallet broadcasts transactions. */
1033 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1034 /** Set whether this wallet broadcasts transactions. */
1035 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1037 /* Find notes filtered by payment address, min depth, ability to spend */
1038 void GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth=1, bool ignoreSpent=true);
1042 /** A key allocated from the key pool. */
1050 CReserveKey(CWallet* pwalletIn)
1053 pwallet = pwalletIn;
1062 virtual bool GetReservedKey(CPubKey &pubkey);
1068 * Account information.
1069 * Stored in wallet with key "acc"+string account name.
1083 vchPubKey = CPubKey();
1086 ADD_SERIALIZE_METHODS;
1088 template <typename Stream, typename Operation>
1089 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1090 if (!(nType & SER_GETHASH))
1091 READWRITE(nVersion);
1092 READWRITE(vchPubKey);
1099 * Internal transfers.
1100 * Database key is acentry<account><counter>.
1102 class CAccountingEntry
1105 std::string strAccount;
1106 CAmount nCreditDebit;
1108 std::string strOtherAccount;
1109 std::string strComment;
1110 mapValue_t mapValue;
1111 int64_t nOrderPos; //! position in ordered transaction list
1124 strOtherAccount.clear();
1130 ADD_SERIALIZE_METHODS;
1132 template <typename Stream, typename Operation>
1133 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1134 if (!(nType & SER_GETHASH))
1135 READWRITE(nVersion);
1136 //! Note: strAccount is serialized as part of the key, not here.
1137 READWRITE(nCreditDebit);
1139 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
1141 if (!ser_action.ForRead())
1143 WriteOrderPos(nOrderPos, mapValue);
1145 if (!(mapValue.empty() && _ssExtra.empty()))
1147 CDataStream ss(nType, nVersion);
1148 ss.insert(ss.begin(), '\0');
1150 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1151 strComment.append(ss.str());
1155 READWRITE(LIMITED_STRING(strComment, 65536));
1157 size_t nSepPos = strComment.find("\0", 0, 1);
1158 if (ser_action.ForRead())
1161 if (std::string::npos != nSepPos)
1163 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1165 _ssExtra = std::vector<char>(ss.begin(), ss.end());
1167 ReadOrderPos(nOrderPos, mapValue);
1169 if (std::string::npos != nSepPos)
1170 strComment.erase(nSepPos);
1172 mapValue.erase("n");
1176 std::vector<char> _ssExtra;
1179 #endif // BITCOIN_WALLET_WALLET_H