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;
280 /** A transaction with a merkle branch linking it to the block chain. */
281 class CMerkleTx : public CTransaction
284 int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
288 std::vector<uint256> vMerkleBranch;
292 mutable bool fMerkleVerified;
300 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
307 hashBlock = uint256();
309 fMerkleVerified = false;
312 ADD_SERIALIZE_METHODS;
314 template <typename Stream, typename Operation>
315 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
316 READWRITE(*(CTransaction*)this);
317 nVersion = this->nVersion;
318 READWRITE(hashBlock);
319 READWRITE(vMerkleBranch);
323 int SetMerkleBranch(const CBlock& block);
327 * Return depth of transaction in blockchain:
328 * -1 : not in blockchain, and not in memory pool (conflicted transaction)
329 * 0 : in memory pool, waiting to be included in a block
330 * >=1 : this many blocks deep in the main chain
332 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
333 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
334 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
335 int GetBlocksToMaturity() const;
336 bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
340 * A transaction with a bunch of additional info that only the owner cares about.
341 * It includes any unrecorded transactions needed to link it back to the block chain.
343 class CWalletTx : public CMerkleTx
346 const CWallet* pwallet;
350 mapNoteData_t mapNoteData;
351 std::vector<std::pair<std::string, std::string> > vOrderForm;
352 unsigned int fTimeReceivedIsTxTime;
353 unsigned int nTimeReceived; //! time received by this node
354 unsigned int nTimeSmart;
356 std::string strFromAccount;
357 int64_t nOrderPos; //! position in ordered transaction list
360 mutable bool fDebitCached;
361 mutable bool fCreditCached;
362 mutable bool fImmatureCreditCached;
363 mutable bool fAvailableCreditCached;
364 mutable bool fWatchDebitCached;
365 mutable bool fWatchCreditCached;
366 mutable bool fImmatureWatchCreditCached;
367 mutable bool fAvailableWatchCreditCached;
368 mutable bool fChangeCached;
369 mutable CAmount nDebitCached;
370 mutable CAmount nCreditCached;
371 mutable CAmount nImmatureCreditCached;
372 mutable CAmount nAvailableCreditCached;
373 mutable CAmount nWatchDebitCached;
374 mutable CAmount nWatchCreditCached;
375 mutable CAmount nImmatureWatchCreditCached;
376 mutable CAmount nAvailableWatchCreditCached;
377 mutable CAmount nChangeCached;
384 CWalletTx(const CWallet* pwalletIn)
389 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
394 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
399 void Init(const CWallet* pwalletIn)
405 fTimeReceivedIsTxTime = false;
409 strFromAccount.clear();
410 fDebitCached = false;
411 fCreditCached = false;
412 fImmatureCreditCached = false;
413 fAvailableCreditCached = false;
414 fWatchDebitCached = false;
415 fWatchCreditCached = false;
416 fImmatureWatchCreditCached = false;
417 fAvailableWatchCreditCached = false;
418 fChangeCached = false;
421 nImmatureCreditCached = 0;
422 nAvailableCreditCached = 0;
423 nWatchDebitCached = 0;
424 nWatchCreditCached = 0;
425 nAvailableWatchCreditCached = 0;
426 nImmatureWatchCreditCached = 0;
431 ADD_SERIALIZE_METHODS;
433 template <typename Stream, typename Operation>
434 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
435 if (ser_action.ForRead())
439 if (!ser_action.ForRead())
441 mapValue["fromaccount"] = strFromAccount;
443 WriteOrderPos(nOrderPos, mapValue);
446 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
449 READWRITE(*(CMerkleTx*)this);
450 std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
453 READWRITE(mapNoteData);
454 READWRITE(vOrderForm);
455 READWRITE(fTimeReceivedIsTxTime);
456 READWRITE(nTimeReceived);
460 if (ser_action.ForRead())
462 strFromAccount = mapValue["fromaccount"];
464 ReadOrderPos(nOrderPos, mapValue);
466 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
469 mapValue.erase("fromaccount");
470 mapValue.erase("version");
471 mapValue.erase("spent");
473 mapValue.erase("timesmart");
476 //! make sure balances are recalculated
479 fCreditCached = false;
480 fAvailableCreditCached = false;
481 fWatchDebitCached = false;
482 fWatchCreditCached = false;
483 fAvailableWatchCreditCached = false;
484 fImmatureWatchCreditCached = false;
485 fDebitCached = false;
486 fChangeCached = false;
489 void BindWallet(CWallet *pwalletIn)
495 void SetNoteData(mapNoteData_t ¬eData);
497 //! filter decides which addresses will count towards the debit
498 CAmount GetDebit(const isminefilter& filter) const;
499 CAmount GetCredit(const isminefilter& filter) const;
500 CAmount GetImmatureCredit(bool fUseCache=true) const;
501 CAmount GetAvailableCredit(bool fUseCache=true) const;
502 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
503 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
504 CAmount GetChange() const;
506 void GetAmounts(std::list<COutputEntry>& listReceived,
507 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
509 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
510 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
512 bool IsFromMe(const isminefilter& filter) const
514 return (GetDebit(filter) > 0);
517 bool IsTrusted() const;
519 bool WriteToDisk(CWalletDB *pwalletdb);
521 int64_t GetTxTime() const;
522 int GetRequestCount() const;
524 bool RelayWalletTransaction();
526 std::set<uint256> GetConflicts() const;
540 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
542 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
545 std::string ToString() const;
551 /** Private key that includes an expiration date in case it never gets used. */
556 int64_t nTimeCreated;
557 int64_t nTimeExpires;
558 std::string strComment;
559 //! todo: add something to note what created it (user, getnewaddress, change)
560 //! maybe should have a map<string, string> property map
562 CWalletKey(int64_t nExpires=0);
564 ADD_SERIALIZE_METHODS;
566 template <typename Stream, typename Operation>
567 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
568 if (!(nType & SER_GETHASH))
570 READWRITE(vchPrivKey);
571 READWRITE(nTimeCreated);
572 READWRITE(nTimeExpires);
573 READWRITE(LIMITED_STRING(strComment, 65536));
578 * Internal transfers.
579 * Database key is acentry<account><counter>.
581 class CAccountingEntry
584 std::string strAccount;
585 CAmount nCreditDebit;
587 std::string strOtherAccount;
588 std::string strComment;
590 int64_t nOrderPos; //! position in ordered transaction list
603 strOtherAccount.clear();
609 ADD_SERIALIZE_METHODS;
611 template <typename Stream, typename Operation>
612 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
613 if (!(nType & SER_GETHASH))
615 //! Note: strAccount is serialized as part of the key, not here.
616 READWRITE(nCreditDebit);
618 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
620 if (!ser_action.ForRead())
622 WriteOrderPos(nOrderPos, mapValue);
624 if (!(mapValue.empty() && _ssExtra.empty()))
626 CDataStream ss(nType, nVersion);
627 ss.insert(ss.begin(), '\0');
629 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
630 strComment.append(ss.str());
634 READWRITE(LIMITED_STRING(strComment, 65536));
636 size_t nSepPos = strComment.find("\0", 0, 1);
637 if (ser_action.ForRead())
640 if (std::string::npos != nSepPos)
642 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
644 _ssExtra = std::vector<char>(ss.begin(), ss.end());
646 ReadOrderPos(nOrderPos, mapValue);
648 if (std::string::npos != nSepPos)
649 strComment.erase(nSepPos);
655 std::vector<char> _ssExtra;
660 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
661 * and provides the ability to create new transactions.
663 class CWallet : public CCryptoKeyStore, public CValidationInterface
666 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;
668 CWalletDB *pwalletdbEncryption;
670 //! the current wallet version: clients below this version are not able to load the wallet
673 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
674 int nWalletMaxVersion;
678 bool fBroadcastTransactions;
681 using TxSpendMap = std::multimap<T, uint256>;
683 * Used to keep track of spent outpoints, and
684 * detect and report conflicts (double-spends or
685 * mutated transactions where the mutant gets mined).
687 typedef TxSpendMap<COutPoint> TxSpends;
688 TxSpends mapTxSpends;
690 * Used to keep track of spent Notes, and
691 * detect and report conflicts (double-spends).
693 typedef TxSpendMap<uint256> TxNullifiers;
694 TxNullifiers mapTxNullifiers;
696 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
697 void AddToSpends(const uint256& nullifier, const uint256& wtxid);
698 void AddToSpends(const uint256& wtxid);
702 * Size of the incremental witness cache for the notes in our wallet.
703 * This will always be greater than or equal to the size of the largest
704 * incremental witness cache in any transaction in mapWallet.
706 int64_t nWitnessCacheSize;
708 void ClearNoteWitnessCache();
712 * pindex is the new tip being connected.
714 void IncrementNoteWitnesses(const CBlockIndex* pindex,
715 const CBlock* pblock,
716 ZCIncrementalMerkleTree& tree);
718 * pindex is the old tip being disconnected.
720 void DecrementNoteWitnesses(const CBlockIndex* pindex);
722 template <typename WalletDB>
723 void SetBestChainINTERNAL(WalletDB& walletdb, const CBlockLocator& loc) {
724 if (!walletdb.TxnBegin()) {
725 // This needs to be done atomically, so don't do it at all
726 LogPrintf("SetBestChain(): Couldn't start atomic write\n");
730 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
731 if (!walletdb.WriteTx(wtxItem.first, wtxItem.second)) {
732 LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
737 if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
738 LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
742 if (!walletdb.WriteBestBlock(loc)) {
743 LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
747 } catch (const std::exception &exc) {
748 // Unexpected failure
749 LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
750 LogPrintf("%s\n", exc.what());
754 if (!walletdb.TxnCommit()) {
755 // Couldn't commit all to db, but in-memory state is fine
756 LogPrintf("SetBestChain(): Couldn't commit atomic write\n");
763 void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
766 bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
767 void MarkAffectedTransactionsDirty(const CTransaction& tx);
772 * This lock protects all the fields added by CWallet
774 * fFileBacked (immutable after instantiation)
775 * strWalletFile (immutable after instantiation)
777 mutable CCriticalSection cs_wallet;
780 std::string strWalletFile;
782 std::set<int64_t> setKeyPool;
783 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
784 std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
786 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
787 MasterKeyMap mapMasterKeys;
788 unsigned int nMasterKeyMaxID;
795 CWallet(const std::string& strWalletFileIn)
799 strWalletFile = strWalletFileIn;
805 delete pwalletdbEncryption;
806 pwalletdbEncryption = NULL;
811 nWalletVersion = FEATURE_BASE;
812 nWalletMaxVersion = FEATURE_BASE;
815 pwalletdbEncryption = NULL;
820 fBroadcastTransactions = false;
821 nWitnessCacheSize = 0;
825 * The reverse mapping of nullifiers to notes.
827 * The mapping cannot be updated while an encrypted wallet is locked,
828 * because we need the SpendingKey to create the nullifier (#1502). This has
829 * several implications for transactions added to the wallet while locked:
831 * - Parent transactions can't be marked dirty when a child transaction that
832 * spends their output notes is updated.
834 * - We currently don't cache any note values, so this is not a problem,
837 * - GetFilteredNotes can't filter out spent notes.
839 * - Per the comment in CNoteData, we assume that if we don't have a
840 * cached nullifier, the note is not spent.
842 * Another more problematic implication is that the wallet can fail to
843 * detect transactions on the blockchain that spend our notes. There are two
844 * possible cases in which this could happen:
846 * - We receive a note when the wallet is locked, and then spend it using a
847 * different wallet client.
849 * - We spend from a PaymentAddress we control, then we export the
850 * SpendingKey and import it into a new wallet, and reindex/rescan to find
851 * the old transactions.
853 * The wallet will only miss "pure" spends - transactions that are only
854 * linked to us by the fact that they contain notes we spent. If it also
855 * sends notes to us, or interacts with our transparent addresses, we will
856 * detect the transaction and add it to the wallet (again without caching
857 * nullifiers for new notes). As by default JoinSplits send change back to
858 * the origin PaymentAddress, the wallet should rarely miss transactions.
860 * To work around these issues, whenever the wallet is unlocked, we scan all
861 * cached notes, and cache any missing nullifiers. Since the wallet must be
862 * unlocked in order to spend notes, this means that GetFilteredNotes will
863 * always behave correctly within that context (and any other uses will give
864 * correct responses afterwards), for the transactions that the wallet was
865 * able to detect. Any missing transactions can be rediscovered by:
867 * - Unlocking the wallet (to fill all nullifier caches).
869 * - Restarting the node with -reindex (which operates on a locked wallet
870 * but with the now-cached nullifiers).
872 std::map<uint256, JSOutPoint> mapNullifiersToNotes;
874 std::map<uint256, CWalletTx> mapWallet;
876 int64_t nOrderPosNext;
877 std::map<uint256, int> mapRequestCount;
879 std::map<CTxDestination, CAddressBookData> mapAddressBook;
881 CPubKey vchDefaultKey;
883 std::set<COutPoint> setLockedCoins;
884 std::set<JSOutPoint> setLockedNotes;
886 int64_t nTimeFirstKey;
888 const CWalletTx* GetWalletTx(const uint256& hash) const;
890 //! check whether we are allowed to upgrade (or already support) to the named feature
891 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
893 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, bool fIncludeCoinBase=true) const;
894 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;
896 bool IsSpent(const uint256& hash, unsigned int n) const;
897 bool IsSpent(const uint256& nullifier) const;
899 bool IsLockedCoin(uint256 hash, unsigned int n) const;
900 void LockCoin(COutPoint& output);
901 void UnlockCoin(COutPoint& output);
902 void UnlockAllCoins();
903 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
905 bool IsLockedNote(uint256 hash, size_t js, uint8_t n) const;
906 void LockNote(JSOutPoint& output);
907 void UnlockNote(JSOutPoint& output);
908 void UnlockAllNotes();
909 std::vector<JSOutPoint> ListLockedNotes();
912 * keystore implementation
915 CPubKey GenerateNewKey();
916 //! Adds a key to the store, and saves it to disk.
917 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
918 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
919 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
920 //! Load metadata (used by LoadWallet)
921 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
923 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
925 //! Adds an encrypted key to the store, and saves it to disk.
926 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
927 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
928 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
929 bool AddCScript(const CScript& redeemScript);
930 bool LoadCScript(const CScript& redeemScript);
932 //! Adds a destination data tuple to the store, and saves it to disk
933 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
934 //! Erases a destination data tuple in the store and on disk
935 bool EraseDestData(const CTxDestination &dest, const std::string &key);
936 //! Adds a destination data tuple to the store, without saving it to disk
937 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
938 //! Look up a destination data tuple in the store, return true if found false otherwise
939 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
941 //! Adds a watch-only address to the store, and saves it to disk.
942 bool AddWatchOnly(const CScript &dest);
943 bool RemoveWatchOnly(const CScript &dest);
944 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
945 bool LoadWatchOnly(const CScript &dest);
947 bool Unlock(const SecureString& strWalletPassphrase);
948 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
949 bool EncryptWallet(const SecureString& strWalletPassphrase);
951 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
956 //! Generates a new zaddr
957 CZCPaymentAddress GenerateNewZKey();
958 //! Adds spending key to the store, and saves it to disk
959 bool AddZKey(const libzcash::SpendingKey &key);
960 //! Adds spending key to the store, without saving it to disk (used by LoadWallet)
961 bool LoadZKey(const libzcash::SpendingKey &key);
962 //! Load spending key metadata (used by LoadWallet)
963 bool LoadZKeyMetadata(const libzcash::PaymentAddress &addr, const CKeyMetadata &meta);
964 //! Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
965 bool LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret);
966 //! Adds an encrypted spending key to the store, and saves it to disk (virtual method, declared in crypter.h)
967 bool AddCryptedSpendingKey(const libzcash::PaymentAddress &address, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret);
969 //! Adds a viewing key to the store, and saves it to disk.
970 bool AddViewingKey(const libzcash::ViewingKey &vk);
971 bool RemoveViewingKey(const libzcash::ViewingKey &vk);
972 //! Adds a viewing key to the store, without saving it to disk (used by LoadWallet)
973 bool LoadViewingKey(const libzcash::ViewingKey &dest);
976 * Increment the next transaction order id
977 * @return next transaction order id
979 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
981 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
982 typedef std::multimap<int64_t, TxPair > TxItems;
985 * Get the wallet's activity log
986 * @return multimap of ordered transactions and accounting entries
987 * @warning Returned pointers are *only* valid within the scope of passed acentries
989 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
992 bool UpdateNullifierNoteMap();
993 void UpdateNullifierNoteMapWithTx(const CWalletTx& wtx);
994 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
995 void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
996 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
997 void EraseFromWallet(const uint256 &hash);
998 void WitnessNoteCommitment(
999 std::vector<uint256> commitments,
1000 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1001 uint256 &final_anchor);
1002 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
1003 void ReacceptWalletTransactions();
1004 void ResendWalletTransactions(int64_t nBestBlockTime);
1005 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
1006 CAmount GetBalance() const;
1007 CAmount GetUnconfirmedBalance() const;
1008 CAmount GetImmatureBalance() const;
1009 CAmount GetWatchOnlyBalance() const;
1010 CAmount GetUnconfirmedWatchOnlyBalance() const;
1011 CAmount GetImmatureWatchOnlyBalance() const;
1012 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason);
1013 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet,
1014 std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true);
1015 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
1017 static CFeeRate minTxFee;
1018 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
1021 bool TopUpKeyPool(unsigned int kpSize = 0);
1022 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
1023 void KeepKey(int64_t nIndex);
1024 void ReturnKey(int64_t nIndex);
1025 bool GetKeyFromPool(CPubKey &key);
1026 int64_t GetOldestKeyPoolTime();
1027 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
1029 std::set< std::set<CTxDestination> > GetAddressGroupings();
1030 std::map<CTxDestination, CAmount> GetAddressBalances();
1032 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
1034 boost::optional<uint256> GetNoteNullifier(
1035 const JSDescription& jsdesc,
1036 const libzcash::PaymentAddress& address,
1037 const ZCNoteDecryption& dec,
1038 const uint256& hSig,
1040 mapNoteData_t FindMyNotes(const CTransaction& tx) const;
1041 bool IsFromMe(const uint256& nullifier) const;
1042 void GetNoteWitnesses(
1043 std::vector<JSOutPoint> notes,
1044 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1045 uint256 &final_anchor);
1047 isminetype IsMine(const CTxIn& txin) const;
1048 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1049 isminetype IsMine(const CTxOut& txout) const;
1050 isminetype IsMine(const CTransaction& tx, uint32_t voutNum);
1051 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1052 bool IsChange(const CTxOut& txout) const;
1053 CAmount GetChange(const CTxOut& txout) const;
1054 bool IsMine(const CTransaction& tx);
1055 /** should probably be renamed to IsRelevantToMe */
1056 bool IsFromMe(const CTransaction& tx) const;
1057 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1058 CAmount GetCredit(const CTransaction& tx, int32_t voutNum, const isminefilter& filter) const;
1059 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1060 CAmount GetChange(const CTransaction& tx) const;
1061 void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, ZCIncrementalMerkleTree tree, bool added);
1062 /** Saves witness caches and best block locator to disk. */
1063 void SetBestChain(const CBlockLocator& loc);
1065 DBErrors LoadWallet(bool& fFirstRunRet);
1066 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1068 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1070 bool DelAddressBook(const CTxDestination& address);
1072 void UpdatedTransaction(const uint256 &hashTx);
1074 void Inventory(const uint256 &hash)
1078 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1079 if (mi != mapRequestCount.end())
1084 unsigned int GetKeyPoolSize()
1086 AssertLockHeld(cs_wallet); // setKeyPool
1087 return setKeyPool.size();
1090 bool SetDefaultKey(const CPubKey &vchPubKey);
1092 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1093 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
1095 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1096 bool SetMaxVersion(int nVersion);
1098 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1099 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1101 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1102 std::set<uint256> GetConflicts(const uint256& txid) const;
1104 //! Flush wallet (bitdb flush)
1105 void Flush(bool shutdown=false);
1107 //! Verify the wallet database and perform salvage if required
1108 static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
1111 * Address book entry changed.
1112 * @note called with lock cs_wallet held.
1114 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1115 &address, const std::string &label, bool isMine,
1116 const std::string &purpose,
1117 ChangeType status)> NotifyAddressBookChanged;
1120 * Wallet transaction added, removed or updated.
1121 * @note called with lock cs_wallet held.
1123 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1124 ChangeType status)> NotifyTransactionChanged;
1126 /** Show progress e.g. for rescan */
1127 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1129 /** Watch-only address added */
1130 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1132 /** Inquire whether this wallet broadcasts transactions. */
1133 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1134 /** Set whether this wallet broadcasts transactions. */
1135 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1137 /* Find notes filtered by payment address, min depth, ability to spend */
1138 void GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries,
1139 std::string address,
1141 bool ignoreSpent=true,
1142 bool ignoreUnspendable=true);
1144 /* Find notes filtered by payment addresses, min depth, ability to spend */
1145 void GetFilteredNotes(std::vector<CNotePlaintextEntry>& outEntries,
1146 std::set<libzcash::PaymentAddress>& filterAddresses,
1148 bool ignoreSpent=true,
1149 bool ignoreUnspendable=true);
1151 // staking functions
1152 bool VerusSelectStakeOutput(CBlock *pBlock, arith_uint256 &hashResult, CTransaction &stakeSource, int32_t &voutNum, int32_t nHeight, uint32_t bnTarget) const;
1153 int32_t VerusStakeTransaction(CBlock *pBlock, CMutableTransaction &txNew, uint32_t bnTarget, arith_uint256 &hashResult, uint8_t *utxosig) const;
1156 /** A key allocated from the key pool. */
1164 CReserveKey(CWallet* pwalletIn)
1167 pwallet = pwalletIn;
1176 virtual bool GetReservedKey(CPubKey &pubkey);
1182 * Account information.
1183 * Stored in wallet with key "acc"+string account name.
1197 vchPubKey = CPubKey();
1200 ADD_SERIALIZE_METHODS;
1202 template <typename Stream, typename Operation>
1203 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1204 if (!(nType & SER_GETHASH))
1205 READWRITE(nVersion);
1206 READWRITE(vchPubKey);
1209 #endif // BITCOIN_WALLET_WALLET_H