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
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 #define _COINBASE_MATURITY 100
62 static const unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10;
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 /** A note outpoint */
162 // Index into CTransaction.vjoinsplit
168 // Index into JSDescription fields of length ZC_NUM_JS_OUTPUTS
171 JSOutPoint() { SetNull(); }
172 JSOutPoint(uint256 h, size_t js, uint8_t n) : hash {h}, js {js}, n {n} { }
174 ADD_SERIALIZE_METHODS;
176 template <typename Stream, typename Operation>
177 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
183 void SetNull() { hash.SetNull(); }
184 bool IsNull() const { return hash.IsNull(); }
186 friend bool operator<(const JSOutPoint& a, const JSOutPoint& b) {
187 return (a.hash < b.hash ||
188 (a.hash == b.hash && a.js < b.js) ||
189 (a.hash == b.hash && a.js == b.js && a.n < b.n));
192 friend bool operator==(const JSOutPoint& a, const JSOutPoint& b) {
193 return (a.hash == b.hash && a.js == b.js && a.n == b.n);
196 friend bool operator!=(const JSOutPoint& a, const JSOutPoint& b) {
200 std::string ToString() const;
206 libzcash::PaymentAddress address;
209 * Cached note nullifier. May not be set if the wallet was not unlocked when
210 * this was CNoteData was created. If not set, we always assume that the
211 * note has not been spent.
213 * It's okay to cache the nullifier in the wallet, because we are storing
214 * the spending key there too, which could be used to derive this.
215 * If the wallet is encrypted, this means that someone with access to the
216 * locked wallet cannot spend notes, but can connect received notes to the
217 * transactions they are spent in. This is the same security semantics as
218 * for transparent addresses.
220 boost::optional<uint256> nullifier;
223 * Cached incremental witnesses for spendable Notes.
224 * Beginning of the list is the most recent witness.
226 std::list<ZCIncrementalWitness> witnesses;
229 * Block height corresponding to the most current witness.
231 * When we first create a CNoteData in CWallet::FindMyNotes, this is set to
232 * -1 as a placeholder. The next time CWallet::ChainTip is called, we can
233 * determine what height the witness cache for this note is valid for (even
234 * if no witnesses were cached), and so can set the correct value in
235 * CWallet::IncrementNoteWitnesses and CWallet::DecrementNoteWitnesses.
239 CNoteData() : address(), nullifier(), witnessHeight {-1} { }
240 CNoteData(libzcash::PaymentAddress a) :
241 address {a}, nullifier(), witnessHeight {-1} { }
242 CNoteData(libzcash::PaymentAddress a, uint256 n) :
243 address {a}, nullifier {n}, witnessHeight {-1} { }
245 ADD_SERIALIZE_METHODS;
247 template <typename Stream, typename Operation>
248 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
250 READWRITE(nullifier);
251 READWRITE(witnesses);
252 READWRITE(witnessHeight);
255 friend bool operator<(const CNoteData& a, const CNoteData& b) {
256 return (a.address < b.address ||
257 (a.address == b.address && a.nullifier < b.nullifier));
260 friend bool operator==(const CNoteData& a, const CNoteData& b) {
261 return (a.address == b.address && a.nullifier == b.nullifier);
264 friend bool operator!=(const CNoteData& a, const CNoteData& b) {
269 typedef std::map<JSOutPoint, CNoteData> mapNoteData_t;
271 /** Decrypted note and its location in a transaction. */
272 struct CNotePlaintextEntry
275 libzcash::PaymentAddress address;
276 libzcash::NotePlaintext plaintext;
281 /** A transaction with a merkle branch linking it to the block chain. */
282 class CMerkleTx : public CTransaction
285 int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
289 std::vector<uint256> vMerkleBranch;
293 mutable bool fMerkleVerified;
301 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
308 hashBlock = uint256();
310 fMerkleVerified = false;
313 ADD_SERIALIZE_METHODS;
315 template <typename Stream, typename Operation>
316 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
317 READWRITE(*(CTransaction*)this);
318 nVersion = this->nVersion;
319 READWRITE(hashBlock);
320 READWRITE(vMerkleBranch);
324 int SetMerkleBranch(const CBlock& block);
328 * Return depth of transaction in blockchain:
329 * -1 : not in blockchain, and not in memory pool (conflicted transaction)
330 * 0 : in memory pool, waiting to be included in a block
331 * >=1 : this many blocks deep in the main chain
333 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
334 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
335 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
336 int GetBlocksToMaturity() const;
337 bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
341 * A transaction with a bunch of additional info that only the owner cares about.
342 * It includes any unrecorded transactions needed to link it back to the block chain.
344 class CWalletTx : public CMerkleTx
347 const CWallet* pwallet;
351 mapNoteData_t mapNoteData;
352 std::vector<std::pair<std::string, std::string> > vOrderForm;
353 unsigned int fTimeReceivedIsTxTime;
354 unsigned int nTimeReceived; //! time received by this node
355 unsigned int nTimeSmart;
357 std::string strFromAccount;
358 int64_t nOrderPos; //! position in ordered transaction list
361 mutable bool fDebitCached;
362 mutable bool fCreditCached;
363 mutable bool fImmatureCreditCached;
364 mutable bool fAvailableCreditCached;
365 mutable bool fWatchDebitCached;
366 mutable bool fWatchCreditCached;
367 mutable bool fImmatureWatchCreditCached;
368 mutable bool fAvailableWatchCreditCached;
369 mutable bool fChangeCached;
370 mutable CAmount nDebitCached;
371 mutable CAmount nCreditCached;
372 mutable CAmount nImmatureCreditCached;
373 mutable CAmount nAvailableCreditCached;
374 mutable CAmount nWatchDebitCached;
375 mutable CAmount nWatchCreditCached;
376 mutable CAmount nImmatureWatchCreditCached;
377 mutable CAmount nAvailableWatchCreditCached;
378 mutable CAmount nChangeCached;
385 CWalletTx(const CWallet* pwalletIn)
390 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
395 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
400 void Init(const CWallet* pwalletIn)
406 fTimeReceivedIsTxTime = false;
410 strFromAccount.clear();
411 fDebitCached = false;
412 fCreditCached = false;
413 fImmatureCreditCached = false;
414 fAvailableCreditCached = false;
415 fWatchDebitCached = false;
416 fWatchCreditCached = false;
417 fImmatureWatchCreditCached = false;
418 fAvailableWatchCreditCached = false;
419 fChangeCached = false;
422 nImmatureCreditCached = 0;
423 nAvailableCreditCached = 0;
424 nWatchDebitCached = 0;
425 nWatchCreditCached = 0;
426 nAvailableWatchCreditCached = 0;
427 nImmatureWatchCreditCached = 0;
432 ADD_SERIALIZE_METHODS;
434 template <typename Stream, typename Operation>
435 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
436 if (ser_action.ForRead())
440 if (!ser_action.ForRead())
442 mapValue["fromaccount"] = strFromAccount;
444 WriteOrderPos(nOrderPos, mapValue);
447 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
450 READWRITE(*(CMerkleTx*)this);
451 std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
454 READWRITE(mapNoteData);
455 READWRITE(vOrderForm);
456 READWRITE(fTimeReceivedIsTxTime);
457 READWRITE(nTimeReceived);
461 if (ser_action.ForRead())
463 strFromAccount = mapValue["fromaccount"];
465 ReadOrderPos(nOrderPos, mapValue);
467 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
470 mapValue.erase("fromaccount");
471 mapValue.erase("version");
472 mapValue.erase("spent");
474 mapValue.erase("timesmart");
477 //! make sure balances are recalculated
480 fCreditCached = false;
481 fAvailableCreditCached = false;
482 fWatchDebitCached = false;
483 fWatchCreditCached = false;
484 fAvailableWatchCreditCached = false;
485 fImmatureWatchCreditCached = false;
486 fDebitCached = false;
487 fChangeCached = false;
490 void BindWallet(CWallet *pwalletIn)
496 void SetNoteData(mapNoteData_t ¬eData);
498 //! filter decides which addresses will count towards the debit
499 CAmount GetDebit(const isminefilter& filter) const;
500 CAmount GetCredit(const isminefilter& filter) const;
501 CAmount GetImmatureCredit(bool fUseCache=true) const;
502 CAmount GetAvailableCredit(bool fUseCache=true) const;
503 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
504 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
505 CAmount GetChange() const;
507 void GetAmounts(std::list<COutputEntry>& listReceived,
508 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
510 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
511 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
513 bool IsFromMe(const isminefilter& filter) const
515 return (GetDebit(filter) > 0);
518 bool IsTrusted() const;
520 bool WriteToDisk(CWalletDB *pwalletdb);
522 int64_t GetTxTime() const;
523 int GetRequestCount() const;
525 bool RelayWalletTransaction();
527 std::set<uint256> GetConflicts() const;
541 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
543 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
546 std::string ToString() const;
552 /** Private key that includes an expiration date in case it never gets used. */
557 int64_t nTimeCreated;
558 int64_t nTimeExpires;
559 std::string strComment;
560 //! todo: add something to note what created it (user, getnewaddress, change)
561 //! maybe should have a map<string, string> property map
563 CWalletKey(int64_t nExpires=0);
565 ADD_SERIALIZE_METHODS;
567 template <typename Stream, typename Operation>
568 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
569 if (!(nType & SER_GETHASH))
571 READWRITE(vchPrivKey);
572 READWRITE(nTimeCreated);
573 READWRITE(nTimeExpires);
574 READWRITE(LIMITED_STRING(strComment, 65536));
579 * Internal transfers.
580 * Database key is acentry<account><counter>.
582 class CAccountingEntry
585 std::string strAccount;
586 CAmount nCreditDebit;
588 std::string strOtherAccount;
589 std::string strComment;
591 int64_t nOrderPos; //! position in ordered transaction list
604 strOtherAccount.clear();
610 ADD_SERIALIZE_METHODS;
612 template <typename Stream, typename Operation>
613 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
614 if (!(nType & SER_GETHASH))
616 //! Note: strAccount is serialized as part of the key, not here.
617 READWRITE(nCreditDebit);
619 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
621 if (!ser_action.ForRead())
623 WriteOrderPos(nOrderPos, mapValue);
625 if (!(mapValue.empty() && _ssExtra.empty()))
627 CDataStream ss(nType, nVersion);
628 ss.insert(ss.begin(), '\0');
630 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
631 strComment.append(ss.str());
635 READWRITE(LIMITED_STRING(strComment, 65536));
637 size_t nSepPos = strComment.find("\0", 0, 1);
638 if (ser_action.ForRead())
641 if (std::string::npos != nSepPos)
643 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
645 _ssExtra = std::vector<char>(ss.begin(), ss.end());
647 ReadOrderPos(nOrderPos, mapValue);
649 if (std::string::npos != nSepPos)
650 strComment.erase(nSepPos);
656 std::vector<char> _ssExtra;
661 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
662 * and provides the ability to create new transactions.
664 class CWallet : public CCryptoKeyStore, public CValidationInterface
667 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;
669 CWalletDB *pwalletdbEncryption;
671 //! the current wallet version: clients below this version are not able to load the wallet
674 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
675 int nWalletMaxVersion;
679 bool fBroadcastTransactions;
682 using TxSpendMap = std::multimap<T, uint256>;
684 * Used to keep track of spent outpoints, and
685 * detect and report conflicts (double-spends or
686 * mutated transactions where the mutant gets mined).
688 typedef TxSpendMap<COutPoint> TxSpends;
689 TxSpends mapTxSpends;
691 * Used to keep track of spent Notes, and
692 * detect and report conflicts (double-spends).
694 typedef TxSpendMap<uint256> TxNullifiers;
695 TxNullifiers mapTxNullifiers;
697 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
698 void AddToSpends(const uint256& nullifier, const uint256& wtxid);
699 void AddToSpends(const uint256& wtxid);
703 * Size of the incremental witness cache for the notes in our wallet.
704 * This will always be greater than or equal to the size of the largest
705 * incremental witness cache in any transaction in mapWallet.
707 int64_t nWitnessCacheSize;
709 void ClearNoteWitnessCache();
713 * pindex is the new tip being connected.
715 void IncrementNoteWitnesses(const CBlockIndex* pindex,
716 const CBlock* pblock,
717 ZCIncrementalMerkleTree& tree);
719 * pindex is the old tip being disconnected.
721 void DecrementNoteWitnesses(const CBlockIndex* pindex);
723 template <typename WalletDB>
724 void SetBestChainINTERNAL(WalletDB& walletdb, const CBlockLocator& loc) {
725 if (!walletdb.TxnBegin()) {
726 // This needs to be done atomically, so don't do it at all
727 LogPrintf("SetBestChain(): Couldn't start atomic write\n");
731 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
732 if (!walletdb.WriteTx(wtxItem.first, wtxItem.second)) {
733 LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
738 if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
739 LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
743 if (!walletdb.WriteBestBlock(loc)) {
744 LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
748 } catch (const std::exception &exc) {
749 // Unexpected failure
750 LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
751 LogPrintf("%s\n", exc.what());
755 if (!walletdb.TxnCommit()) {
756 // Couldn't commit all to db, but in-memory state is fine
757 LogPrintf("SetBestChain(): Couldn't commit atomic write\n");
764 void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
767 bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
768 void MarkAffectedTransactionsDirty(const CTransaction& tx);
773 * This lock protects all the fields added by CWallet
775 * fFileBacked (immutable after instantiation)
776 * strWalletFile (immutable after instantiation)
778 mutable CCriticalSection cs_wallet;
781 std::string strWalletFile;
783 std::set<int64_t> setKeyPool;
784 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
785 std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
787 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
788 MasterKeyMap mapMasterKeys;
789 unsigned int nMasterKeyMaxID;
796 CWallet(const std::string& strWalletFileIn)
800 strWalletFile = strWalletFileIn;
806 delete pwalletdbEncryption;
807 pwalletdbEncryption = NULL;
812 nWalletVersion = FEATURE_BASE;
813 nWalletMaxVersion = FEATURE_BASE;
816 pwalletdbEncryption = NULL;
821 fBroadcastTransactions = false;
822 nWitnessCacheSize = 0;
826 * The reverse mapping of nullifiers to notes.
828 * The mapping cannot be updated while an encrypted wallet is locked,
829 * because we need the SpendingKey to create the nullifier (#1502). This has
830 * several implications for transactions added to the wallet while locked:
832 * - Parent transactions can't be marked dirty when a child transaction that
833 * spends their output notes is updated.
835 * - We currently don't cache any note values, so this is not a problem,
838 * - GetFilteredNotes can't filter out spent notes.
840 * - Per the comment in CNoteData, we assume that if we don't have a
841 * cached nullifier, the note is not spent.
843 * Another more problematic implication is that the wallet can fail to
844 * detect transactions on the blockchain that spend our notes. There are two
845 * possible cases in which this could happen:
847 * - We receive a note when the wallet is locked, and then spend it using a
848 * different wallet client.
850 * - We spend from a PaymentAddress we control, then we export the
851 * SpendingKey and import it into a new wallet, and reindex/rescan to find
852 * the old transactions.
854 * The wallet will only miss "pure" spends - transactions that are only
855 * linked to us by the fact that they contain notes we spent. If it also
856 * sends notes to us, or interacts with our transparent addresses, we will
857 * detect the transaction and add it to the wallet (again without caching
858 * nullifiers for new notes). As by default JoinSplits send change back to
859 * the origin PaymentAddress, the wallet should rarely miss transactions.
861 * To work around these issues, whenever the wallet is unlocked, we scan all
862 * cached notes, and cache any missing nullifiers. Since the wallet must be
863 * unlocked in order to spend notes, this means that GetFilteredNotes will
864 * always behave correctly within that context (and any other uses will give
865 * correct responses afterwards), for the transactions that the wallet was
866 * able to detect. Any missing transactions can be rediscovered by:
868 * - Unlocking the wallet (to fill all nullifier caches).
870 * - Restarting the node with -reindex (which operates on a locked wallet
871 * but with the now-cached nullifiers).
873 std::map<uint256, JSOutPoint> mapNullifiersToNotes;
875 std::map<uint256, CWalletTx> mapWallet;
877 int64_t nOrderPosNext;
878 std::map<uint256, int> mapRequestCount;
880 std::map<CTxDestination, CAddressBookData> mapAddressBook;
882 CPubKey vchDefaultKey;
884 std::set<COutPoint> setLockedCoins;
885 std::set<JSOutPoint> setLockedNotes;
887 int64_t nTimeFirstKey;
889 const CWalletTx* GetWalletTx(const uint256& hash) const;
891 //! check whether we are allowed to upgrade (or already support) to the named feature
892 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
894 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, bool fIncludeCoinBase=true) const;
895 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;
897 bool IsSpent(const uint256& hash, unsigned int n) const;
898 bool IsSpent(const uint256& nullifier) const;
900 bool IsLockedCoin(uint256 hash, unsigned int n) const;
901 void LockCoin(COutPoint& output);
902 void UnlockCoin(COutPoint& output);
903 void UnlockAllCoins();
904 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
907 bool IsLockedNote(uint256 hash, size_t js, uint8_t n) const;
908 void LockNote(JSOutPoint& output);
909 void UnlockNote(JSOutPoint& output);
910 void UnlockAllNotes();
911 std::vector<JSOutPoint> ListLockedNotes();
915 * keystore implementation
918 CPubKey GenerateNewKey();
919 //! Adds a key to the store, and saves it to disk.
920 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
921 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
922 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
923 //! Load metadata (used by LoadWallet)
924 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
926 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
928 //! Adds an encrypted key to the store, and saves it to disk.
929 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
930 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
931 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
932 bool AddCScript(const CScript& redeemScript);
933 bool LoadCScript(const CScript& redeemScript);
935 //! Adds a destination data tuple to the store, and saves it to disk
936 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
937 //! Erases a destination data tuple in the store and on disk
938 bool EraseDestData(const CTxDestination &dest, const std::string &key);
939 //! Adds a destination data tuple to the store, without saving it to disk
940 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
941 //! Look up a destination data tuple in the store, return true if found false otherwise
942 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
944 //! Adds a watch-only address to the store, and saves it to disk.
945 bool AddWatchOnly(const CScript &dest);
946 bool RemoveWatchOnly(const CScript &dest);
947 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
948 bool LoadWatchOnly(const CScript &dest);
950 bool Unlock(const SecureString& strWalletPassphrase);
951 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
952 bool EncryptWallet(const SecureString& strWalletPassphrase);
954 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
959 //! Generates a new zaddr
960 CZCPaymentAddress GenerateNewZKey();
961 //! Adds spending key to the store, and saves it to disk
962 bool AddZKey(const libzcash::SpendingKey &key);
963 //! Adds spending key to the store, without saving it to disk (used by LoadWallet)
964 bool LoadZKey(const libzcash::SpendingKey &key);
965 //! Load spending key metadata (used by LoadWallet)
966 bool LoadZKeyMetadata(const libzcash::PaymentAddress &addr, const CKeyMetadata &meta);
967 //! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
968 bool LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret);
969 //! Adds an encrypted spending key to the store, and saves it to disk (virtual method, declared in crypter.h)
970 bool AddCryptedSpendingKey(const libzcash::PaymentAddress &address, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret);
972 //! Adds a viewing key to the store, and saves it to disk.
973 bool AddViewingKey(const libzcash::ViewingKey &vk);
974 bool RemoveViewingKey(const libzcash::ViewingKey &vk);
975 //! Adds a viewing key to the store, without saving it to disk (used by LoadWallet)
976 bool LoadViewingKey(const libzcash::ViewingKey &dest);
979 * Increment the next transaction order id
980 * @return next transaction order id
982 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
984 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
985 typedef std::multimap<int64_t, TxPair > TxItems;
988 * Get the wallet's activity log
989 * @return multimap of ordered transactions and accounting entries
990 * @warning Returned pointers are *only* valid within the scope of passed acentries
992 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
995 bool UpdateNullifierNoteMap();
996 void UpdateNullifierNoteMapWithTx(const CWalletTx& wtx);
997 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
998 void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
999 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
1000 void EraseFromWallet(const uint256 &hash);
1001 void WitnessNoteCommitment(
1002 std::vector<uint256> commitments,
1003 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1004 uint256 &final_anchor);
1005 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
1006 void ReacceptWalletTransactions();
1007 void ResendWalletTransactions(int64_t nBestBlockTime);
1008 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
1009 CAmount GetBalance() const;
1010 CAmount GetUnconfirmedBalance() const;
1011 CAmount GetImmatureBalance() const;
1012 CAmount GetWatchOnlyBalance() const;
1013 CAmount GetUnconfirmedWatchOnlyBalance() const;
1014 CAmount GetImmatureWatchOnlyBalance() const;
1015 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason);
1016 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet,
1017 std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true);
1018 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
1020 static CFeeRate minTxFee;
1021 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
1024 bool TopUpKeyPool(unsigned int kpSize = 0);
1025 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
1026 void KeepKey(int64_t nIndex);
1027 void ReturnKey(int64_t nIndex);
1028 bool GetKeyFromPool(CPubKey &key);
1029 int64_t GetOldestKeyPoolTime();
1030 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
1032 std::set< std::set<CTxDestination> > GetAddressGroupings();
1033 std::map<CTxDestination, CAmount> GetAddressBalances();
1035 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
1037 boost::optional<uint256> GetNoteNullifier(
1038 const JSDescription& jsdesc,
1039 const libzcash::PaymentAddress& address,
1040 const ZCNoteDecryption& dec,
1041 const uint256& hSig,
1043 mapNoteData_t FindMyNotes(const CTransaction& tx) const;
1044 bool IsFromMe(const uint256& nullifier) const;
1045 void GetNoteWitnesses(
1046 std::vector<JSOutPoint> notes,
1047 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1048 uint256 &final_anchor);
1050 isminetype IsMine(const CTxIn& txin) const;
1051 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1052 isminetype IsMine(const CTxOut& txout) const;
1053 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1054 bool IsChange(const CTxOut& txout) const;
1055 CAmount GetChange(const CTxOut& txout) const;
1056 bool IsMine(const CTransaction& tx) const;
1057 /** should probably be renamed to IsRelevantToMe */
1058 bool IsFromMe(const CTransaction& tx) const;
1059 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1060 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1061 CAmount GetChange(const CTransaction& tx) const;
1062 void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, ZCIncrementalMerkleTree tree, bool added);
1063 /** Saves witness caches and best block locator to disk. */
1064 void SetBestChain(const CBlockLocator& loc);
1066 DBErrors LoadWallet(bool& fFirstRunRet);
1067 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1069 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1071 bool DelAddressBook(const CTxDestination& address);
1073 void UpdatedTransaction(const uint256 &hashTx);
1075 void Inventory(const uint256 &hash)
1079 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1080 if (mi != mapRequestCount.end())
1085 unsigned int GetKeyPoolSize()
1087 AssertLockHeld(cs_wallet); // setKeyPool
1088 return setKeyPool.size();
1091 bool SetDefaultKey(const CPubKey &vchPubKey);
1093 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1094 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
1096 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1097 bool SetMaxVersion(int nVersion);
1099 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1100 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1102 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1103 std::set<uint256> GetConflicts(const uint256& txid) const;
1105 //! Flush wallet (bitdb flush)
1106 void Flush(bool shutdown=false);
1108 //! Verify the wallet database and perform salvage if required
1109 static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
1112 * Address book entry changed.
1113 * @note called with lock cs_wallet held.
1115 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1116 &address, const std::string &label, bool isMine,
1117 const std::string &purpose,
1118 ChangeType status)> NotifyAddressBookChanged;
1121 * Wallet transaction added, removed or updated.
1122 * @note called with lock cs_wallet held.
1124 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1125 ChangeType status)> NotifyTransactionChanged;
1127 /** Show progress e.g. for rescan */
1128 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1130 /** Watch-only address added */
1131 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1133 /** Inquire whether this wallet broadcasts transactions. */
1134 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1135 /** Set whether this wallet broadcasts transactions. */
1136 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1138 /* Find notes filtered by payment address, min depth, ability to spend */
1139 void GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries,
1140 std::string address,
1142 bool ignoreSpent=true,
1143 bool ignoreUnspendable=true);
1145 /* Find notes filtered by payment addresses, min depth, ability to spend */
1146 void GetFilteredNotes(std::vector<CNotePlaintextEntry>& outEntries,
1147 std::set<libzcash::PaymentAddress>& filterAddresses,
1149 bool ignoreSpent=true,
1150 bool ignoreUnspendable=true);
1154 /** A key allocated from the key pool. */
1162 CReserveKey(CWallet* pwalletIn)
1165 pwallet = pwalletIn;
1174 virtual bool GetReservedKey(CPubKey &pubkey);
1180 * Account information.
1181 * Stored in wallet with key "acc"+string account name.
1195 vchPubKey = CPubKey();
1198 ADD_SERIALIZE_METHODS;
1200 template <typename Stream, typename Operation>
1201 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1202 if (!(nType & SER_GETHASH))
1203 READWRITE(nVersion);
1204 READWRITE(vchPubKey);
1207 #endif // BITCOIN_WALLET_WALLET_H