]> Git Repo - VerusCoin.git/blob - src/wallet/wallet.h
use const references where appropriate
[VerusCoin.git] / src / wallet / wallet.h
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.
5
6 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
8
9 #include "amount.h"
10 #include "coins.h"
11 #include "consensus/consensus.h"
12 #include "key.h"
13 #include "keystore.h"
14 #include "primitives/block.h"
15 #include "primitives/transaction.h"
16 #include "tinyformat.h"
17 #include "ui_interface.h"
18 #include "util.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"
25 #include "base58.h"
26
27 #include <algorithm>
28 #include <map>
29 #include <set>
30 #include <stdexcept>
31 #include <stdint.h>
32 #include <string>
33 #include <utility>
34 #include <vector>
35
36 /**
37  * Settings
38  */
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;
45
46 //! -paytxfee default
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;
50 //! -maxtxfee default
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;
62
63 class CAccountingEntry;
64 class CBlockIndex;
65 class CCoinControl;
66 class COutput;
67 class CReserveKey;
68 class CScript;
69 class CTxMemPool;
70 class CWalletTx;
71
72 /** (client) version numbers for particular wallet features */
73 enum WalletFeature
74 {
75     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
76
77     FEATURE_WALLETCRYPT = 40000, // wallet encryption
78     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
79
80     FEATURE_LATEST = 60000
81 };
82
83
84 /** A key pool entry */
85 class CKeyPool
86 {
87 public:
88     int64_t nTime;
89     CPubKey vchPubKey;
90
91     CKeyPool();
92     CKeyPool(const CPubKey& vchPubKeyIn);
93
94     ADD_SERIALIZE_METHODS;
95
96     template <typename Stream, typename Operation>
97     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
98         if (!(nType & SER_GETHASH))
99             READWRITE(nVersion);
100         READWRITE(nTime);
101         READWRITE(vchPubKey);
102     }
103 };
104
105 /** Address book data */
106 class CAddressBookData
107 {
108 public:
109     std::string name;
110     std::string purpose;
111
112     CAddressBookData()
113     {
114         purpose = "unknown";
115     }
116
117     typedef std::map<std::string, std::string> StringMap;
118     StringMap destdata;
119 };
120
121 struct CRecipient
122 {
123     CScript scriptPubKey;
124     CAmount nAmount;
125     bool fSubtractFeeFromAmount;
126 };
127
128 typedef std::map<std::string, std::string> mapValue_t;
129
130
131 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
132 {
133     if (!mapValue.count("n"))
134     {
135         nOrderPos = -1; // TODO: calculate elsewhere
136         return;
137     }
138     nOrderPos = atoi64(mapValue["n"].c_str());
139 }
140
141
142 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
143 {
144     if (nOrderPos == -1)
145         return;
146     mapValue["n"] = i64tostr(nOrderPos);
147 }
148
149 struct COutputEntry
150 {
151     CTxDestination destination;
152     CAmount amount;
153     int vout;
154 };
155
156 /** An note outpoint */
157 class JSOutPoint
158 {
159 public:
160     // Transaction hash
161     uint256 hash;
162     // Index into CTransaction.vjoinsplit
163     size_t js;
164     // Index into JSDescription fields of length ZC_NUM_JS_OUTPUTS
165     uint8_t n;
166
167     JSOutPoint() { SetNull(); }
168     JSOutPoint(uint256 h, size_t js, uint8_t n) : hash {h}, js {js}, n {n} { }
169
170     ADD_SERIALIZE_METHODS;
171
172     template <typename Stream, typename Operation>
173     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
174         READWRITE(hash);
175         READWRITE(js);
176         READWRITE(n);
177     }
178
179     void SetNull() { hash.SetNull(); }
180     bool IsNull() const { return hash.IsNull(); }
181
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));
186     }
187
188     friend bool operator==(const JSOutPoint& a, const JSOutPoint& b) {
189         return (a.hash == b.hash && a.js == b.js && a.n == b.n);
190     }
191
192     friend bool operator!=(const JSOutPoint& a, const JSOutPoint& b) {
193         return !(a == b);
194     }
195
196     std::string ToString() const;
197 };
198
199 class CNoteData
200 {
201 public:
202     libzcash::PaymentAddress address;
203
204     /**
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.
208      *
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.
215      */
216     boost::optional<uint256> nullifier;
217
218     /**
219      * Cached incremental witnesses for spendable Notes.
220      * Beginning of the list is the most recent witness.
221      */
222     std::list<ZCIncrementalWitness> witnesses;
223
224     /**
225      * Block height corresponding to the most current witness.
226      *
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.
232      */
233     int witnessHeight;
234
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} { }
240
241     ADD_SERIALIZE_METHODS;
242
243     template <typename Stream, typename Operation>
244     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
245         READWRITE(address);
246         READWRITE(nullifier);
247         READWRITE(witnesses);
248         READWRITE(witnessHeight);
249     }
250
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));
254     }
255
256     friend bool operator==(const CNoteData& a, const CNoteData& b) {
257         return (a.address == b.address && a.nullifier == b.nullifier);
258     }
259
260     friend bool operator!=(const CNoteData& a, const CNoteData& b) {
261         return !(a == b);
262     }
263 };
264
265 typedef std::map<JSOutPoint, CNoteData> mapNoteData_t;
266
267 /** Decrypted note and its location in a transaction. */
268 struct CNotePlaintextEntry
269 {
270     JSOutPoint jsop;
271     libzcash::NotePlaintext plaintext;
272 };
273
274
275
276 /** A transaction with a merkle branch linking it to the block chain. */
277 class CMerkleTx : public CTransaction
278 {
279 private:
280     int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
281
282 public:
283     uint256 hashBlock;
284     std::vector<uint256> vMerkleBranch;
285     int nIndex;
286
287     // memory only
288     mutable bool fMerkleVerified;
289
290
291     CMerkleTx()
292     {
293         Init();
294     }
295
296     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
297     {
298         Init();
299     }
300
301     void Init()
302     {
303         hashBlock = uint256();
304         nIndex = -1;
305         fMerkleVerified = false;
306     }
307
308     ADD_SERIALIZE_METHODS;
309
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);
316         READWRITE(nIndex);
317     }
318
319     int SetMerkleBranch(const CBlock& block);
320
321
322     /**
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
327      */
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);
333 };
334
335 /** 
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.
338  */
339 class CWalletTx : public CMerkleTx
340 {
341 private:
342     const CWallet* pwallet;
343
344 public:
345     mapValue_t mapValue;
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;
351     char fFromMe;
352     std::string strFromAccount;
353     int64_t nOrderPos; //! position in ordered transaction list
354
355     // memory only
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;
374
375     CWalletTx()
376     {
377         Init(NULL);
378     }
379
380     CWalletTx(const CWallet* pwalletIn)
381     {
382         Init(pwalletIn);
383     }
384
385     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
386     {
387         Init(pwalletIn);
388     }
389
390     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
391     {
392         Init(pwalletIn);
393     }
394
395     void Init(const CWallet* pwalletIn)
396     {
397         pwallet = pwalletIn;
398         mapValue.clear();
399         mapNoteData.clear();
400         vOrderForm.clear();
401         fTimeReceivedIsTxTime = false;
402         nTimeReceived = 0;
403         nTimeSmart = 0;
404         fFromMe = 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;
415         nDebitCached = 0;
416         nCreditCached = 0;
417         nImmatureCreditCached = 0;
418         nAvailableCreditCached = 0;
419         nWatchDebitCached = 0;
420         nWatchCreditCached = 0;
421         nAvailableWatchCreditCached = 0;
422         nImmatureWatchCreditCached = 0;
423         nChangeCached = 0;
424         nOrderPos = -1;
425     }
426
427     ADD_SERIALIZE_METHODS;
428
429     template <typename Stream, typename Operation>
430     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
431         if (ser_action.ForRead())
432             Init(NULL);
433         char fSpent = false;
434
435         if (!ser_action.ForRead())
436         {
437             mapValue["fromaccount"] = strFromAccount;
438
439             WriteOrderPos(nOrderPos, mapValue);
440
441             if (nTimeSmart)
442                 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
443         }
444
445         READWRITE(*(CMerkleTx*)this);
446         std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
447         READWRITE(vUnused);
448         READWRITE(mapValue);
449         READWRITE(mapNoteData);
450         READWRITE(vOrderForm);
451         READWRITE(fTimeReceivedIsTxTime);
452         READWRITE(nTimeReceived);
453         READWRITE(fFromMe);
454         READWRITE(fSpent);
455
456         if (ser_action.ForRead())
457         {
458             strFromAccount = mapValue["fromaccount"];
459
460             ReadOrderPos(nOrderPos, mapValue);
461
462             nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
463         }
464
465         mapValue.erase("fromaccount");
466         mapValue.erase("version");
467         mapValue.erase("spent");
468         mapValue.erase("n");
469         mapValue.erase("timesmart");
470     }
471
472     //! make sure balances are recalculated
473     void MarkDirty()
474     {
475         fCreditCached = false;
476         fAvailableCreditCached = false;
477         fWatchDebitCached = false;
478         fWatchCreditCached = false;
479         fAvailableWatchCreditCached = false;
480         fImmatureWatchCreditCached = false;
481         fDebitCached = false;
482         fChangeCached = false;
483     }
484
485     void BindWallet(CWallet *pwalletIn)
486     {
487         pwallet = pwalletIn;
488         MarkDirty();
489     }
490
491     void SetNoteData(mapNoteData_t &noteData);
492
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;
501
502     void GetAmounts(std::list<COutputEntry>& listReceived,
503                     std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
504
505     void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
506                            CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
507
508     bool IsFromMe(const isminefilter& filter) const
509     {
510         return (GetDebit(filter) > 0);
511     }
512
513     bool IsTrusted() const;
514
515     bool WriteToDisk(CWalletDB *pwalletdb);
516
517     int64_t GetTxTime() const;
518     int GetRequestCount() const;
519
520     bool RelayWalletTransaction();
521
522     std::set<uint256> GetConflicts() const;
523 };
524
525
526
527
528 class COutput
529 {
530 public:
531     const CWalletTx *tx;
532     int i;
533     int nDepth;
534     bool fSpendable;
535
536     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
537     {
538         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
539     }
540
541     std::string ToString() const;
542 };
543
544
545
546
547 /** Private key that includes an expiration date in case it never gets used. */
548 class CWalletKey
549 {
550 public:
551     CPrivKey vchPrivKey;
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
557
558     CWalletKey(int64_t nExpires=0);
559
560     ADD_SERIALIZE_METHODS;
561
562     template <typename Stream, typename Operation>
563     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
564         if (!(nType & SER_GETHASH))
565             READWRITE(nVersion);
566         READWRITE(vchPrivKey);
567         READWRITE(nTimeCreated);
568         READWRITE(nTimeExpires);
569         READWRITE(LIMITED_STRING(strComment, 65536));
570     }
571 };
572
573
574
575 /** 
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.
578  */
579 class CWallet : public CCryptoKeyStore, public CValidationInterface
580 {
581 private:
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;
583
584     CWalletDB *pwalletdbEncryption;
585
586     //! the current wallet version: clients below this version are not able to load the wallet
587     int nWalletVersion;
588
589     //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
590     int nWalletMaxVersion;
591
592     int64_t nNextResend;
593     int64_t nLastResend;
594     bool fBroadcastTransactions;
595
596     template <class T>
597     using TxSpendMap = std::multimap<T, uint256>;
598     /**
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).
602      */
603     typedef TxSpendMap<COutPoint> TxSpends;
604     TxSpends mapTxSpends;
605     /**
606      * Used to keep track of spent Notes, and
607      * detect and report conflicts (double-spends).
608      */
609     typedef TxSpendMap<uint256> TxNullifiers;
610     TxNullifiers mapTxNullifiers;
611
612     void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
613     void AddToSpends(const uint256& nullifier, const uint256& wtxid);
614     void AddToSpends(const uint256& wtxid);
615
616 public:
617     /*
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.
621      */
622     int64_t nWitnessCacheSize;
623
624     void ClearNoteWitnessCache();
625
626 protected:
627     /**
628      * pindex is the new tip being connected.
629      */
630     void IncrementNoteWitnesses(const CBlockIndex* pindex,
631                                 const CBlock* pblock,
632                                 ZCIncrementalMerkleTree& tree);
633     /**
634      * pindex is the old tip being disconnected.
635      */
636     void DecrementNoteWitnesses(const CBlockIndex* pindex);
637
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");
643             return;
644         }
645         try {
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");
649                     walletdb.TxnAbort();
650                     return;
651                 }
652             }
653             if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
654                 LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
655                 walletdb.TxnAbort();
656                 return;
657             }
658             if (!walletdb.WriteBestBlock(loc)) {
659                 LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
660                 walletdb.TxnAbort();
661                 return;
662             }
663         } catch (const std::exception &exc) {
664             // Unexpected failure
665             LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
666             LogPrintf("%s\n", exc.what());
667             walletdb.TxnAbort();
668             return;
669         }
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");
673             return;
674         }
675     }
676
677 private:
678     template <class T>
679     void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
680
681 protected:
682     bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
683     void MarkAffectedTransactionsDirty(const CTransaction& tx);
684
685 public:
686     /*
687      * Main wallet lock.
688      * This lock protects all the fields added by CWallet
689      *   except for:
690      *      fFileBacked (immutable after instantiation)
691      *      strWalletFile (immutable after instantiation)
692      */
693     mutable CCriticalSection cs_wallet;
694
695     bool fFileBacked;
696     std::string strWalletFile;
697
698     std::set<int64_t> setKeyPool;
699     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
700     std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
701
702     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
703     MasterKeyMap mapMasterKeys;
704     unsigned int nMasterKeyMaxID;
705
706     CWallet()
707     {
708         SetNull();
709     }
710
711     CWallet(const std::string& strWalletFileIn)
712     {
713         SetNull();
714
715         strWalletFile = strWalletFileIn;
716         fFileBacked = true;
717     }
718
719     ~CWallet()
720     {
721         delete pwalletdbEncryption;
722         pwalletdbEncryption = NULL;
723     }
724
725     void SetNull()
726     {
727         nWalletVersion = FEATURE_BASE;
728         nWalletMaxVersion = FEATURE_BASE;
729         fFileBacked = false;
730         nMasterKeyMaxID = 0;
731         pwalletdbEncryption = NULL;
732         nOrderPosNext = 0;
733         nNextResend = 0;
734         nLastResend = 0;
735         nTimeFirstKey = 0;
736         fBroadcastTransactions = false;
737         nWitnessCacheSize = 0;
738     }
739
740     /**
741      * The reverse mapping of nullifiers to notes.
742      *
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:
746      *
747      * - Parent transactions can't be marked dirty when a child transaction that
748      *   spends their output notes is updated.
749      *
750      *   - We currently don't cache any note values, so this is not a problem,
751      *     yet.
752      *
753      * - GetFilteredNotes can't filter out spent notes.
754      *
755      *   - Per the comment in CNoteData, we assume that if we don't have a
756      *     cached nullifier, the note is not spent.
757      *
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:
761      *
762      * - We receive a note when the wallet is locked, and then spend it using a
763      *   different wallet client.
764      *
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.
768      *
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.
775      *
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:
782      *
783      * - Unlocking the wallet (to fill all nullifier caches).
784      *
785      * - Restarting the node with -reindex (which operates on a locked wallet
786      *   but with the now-cached nullifiers).
787      */
788     std::map<uint256, JSOutPoint> mapNullifiersToNotes;
789
790     std::map<uint256, CWalletTx> mapWallet;
791
792     int64_t nOrderPosNext;
793     std::map<uint256, int> mapRequestCount;
794
795     std::map<CTxDestination, CAddressBookData> mapAddressBook;
796
797     CPubKey vchDefaultKey;
798
799     std::set<COutPoint> setLockedCoins;
800
801     int64_t nTimeFirstKey;
802
803     const CWalletTx* GetWalletTx(const uint256& hash) const;
804
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; }
807
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;
810
811     bool IsSpent(const uint256& hash, unsigned int n) const;
812     bool IsSpent(const uint256& nullifier) const;
813
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);
819
820     /**
821      * keystore implementation
822      * Generate a new key
823      */
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);
831
832     bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
833
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);
840
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;
849
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);
855
856     bool Unlock(const SecureString& strWalletPassphrase);
857     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
858     bool EncryptWallet(const SecureString& strWalletPassphrase);
859
860     void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
861
862     /**
863       * ZKeys
864       */
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);
877
878     /** 
879      * Increment the next transaction order id
880      * @return next transaction order id
881      */
882     int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
883
884     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
885     typedef std::multimap<int64_t, TxPair > TxItems;
886
887     /**
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
891      */
892     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
893
894     void MarkDirty();
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);
918
919     static CFeeRate minTxFee;
920     static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
921
922     bool NewKeyPool();
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;
930
931     std::set< std::set<CTxDestination> > GetAddressGroupings();
932     std::map<CTxDestination, CAmount> GetAddressBalances();
933
934     std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
935
936     boost::optional<uint256> GetNoteNullifier(
937         const JSDescription& jsdesc,
938         const libzcash::PaymentAddress& address,
939         const ZCNoteDecryption& dec,
940         const uint256& hSig,
941         uint8_t n) const;
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);
948
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);
964
965     DBErrors LoadWallet(bool& fFirstRunRet);
966     DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
967
968     bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
969
970     bool DelAddressBook(const CTxDestination& address);
971
972     void UpdatedTransaction(const uint256 &hashTx);
973
974     void Inventory(const uint256 &hash)
975     {
976         {
977             LOCK(cs_wallet);
978             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
979             if (mi != mapRequestCount.end())
980                 (*mi).second++;
981         }
982     }
983
984     unsigned int GetKeyPoolSize()
985     {
986         AssertLockHeld(cs_wallet); // setKeyPool
987         return setKeyPool.size();
988     }
989
990     bool SetDefaultKey(const CPubKey &vchPubKey);
991
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);
994
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);
997
998     //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
999     int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1000
1001     //! Get wallet transactions that conflict with given transaction (spend same outputs)
1002     std::set<uint256> GetConflicts(const uint256& txid) const;
1003
1004     //! Flush wallet (bitdb flush)
1005     void Flush(bool shutdown=false);
1006
1007     //! Verify the wallet database and perform salvage if required
1008     static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
1009     
1010     /** 
1011      * Address book entry changed.
1012      * @note called with lock cs_wallet held.
1013      */
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;
1018
1019     /** 
1020      * Wallet transaction added, removed or updated.
1021      * @note called with lock cs_wallet held.
1022      */
1023     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1024             ChangeType status)> NotifyTransactionChanged;
1025
1026     /** Show progress e.g. for rescan */
1027     boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1028
1029     /** Watch-only address added */
1030     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1031
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; }
1036     
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);
1039     
1040 };
1041
1042 /** A key allocated from the key pool. */
1043 class CReserveKey
1044 {
1045 protected:
1046     CWallet* pwallet;
1047     int64_t nIndex;
1048     CPubKey vchPubKey;
1049 public:
1050     CReserveKey(CWallet* pwalletIn)
1051     {
1052         nIndex = -1;
1053         pwallet = pwalletIn;
1054     }
1055
1056     ~CReserveKey()
1057     {
1058         ReturnKey();
1059     }
1060
1061     void ReturnKey();
1062     virtual bool GetReservedKey(CPubKey &pubkey);
1063     void KeepKey();
1064 };
1065
1066
1067 /** 
1068  * Account information.
1069  * Stored in wallet with key "acc"+string account name.
1070  */
1071 class CAccount
1072 {
1073 public:
1074     CPubKey vchPubKey;
1075
1076     CAccount()
1077     {
1078         SetNull();
1079     }
1080
1081     void SetNull()
1082     {
1083         vchPubKey = CPubKey();
1084     }
1085
1086     ADD_SERIALIZE_METHODS;
1087
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);
1093     }
1094 };
1095
1096
1097
1098 /** 
1099  * Internal transfers.
1100  * Database key is acentry<account><counter>.
1101  */
1102 class CAccountingEntry
1103 {
1104 public:
1105     std::string strAccount;
1106     CAmount nCreditDebit;
1107     int64_t nTime;
1108     std::string strOtherAccount;
1109     std::string strComment;
1110     mapValue_t mapValue;
1111     int64_t nOrderPos;  //! position in ordered transaction list
1112     uint64_t nEntryNo;
1113
1114     CAccountingEntry()
1115     {
1116         SetNull();
1117     }
1118
1119     void SetNull()
1120     {
1121         nCreditDebit = 0;
1122         nTime = 0;
1123         strAccount.clear();
1124         strOtherAccount.clear();
1125         strComment.clear();
1126         nOrderPos = -1;
1127         nEntryNo = 0;
1128     }
1129
1130     ADD_SERIALIZE_METHODS;
1131
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);
1138         READWRITE(nTime);
1139         READWRITE(LIMITED_STRING(strOtherAccount, 65536));
1140
1141         if (!ser_action.ForRead())
1142         {
1143             WriteOrderPos(nOrderPos, mapValue);
1144
1145             if (!(mapValue.empty() && _ssExtra.empty()))
1146             {
1147                 CDataStream ss(nType, nVersion);
1148                 ss.insert(ss.begin(), '\0');
1149                 ss << mapValue;
1150                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1151                 strComment.append(ss.str());
1152             }
1153         }
1154
1155         READWRITE(LIMITED_STRING(strComment, 65536));
1156
1157         size_t nSepPos = strComment.find("\0", 0, 1);
1158         if (ser_action.ForRead())
1159         {
1160             mapValue.clear();
1161             if (std::string::npos != nSepPos)
1162             {
1163                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1164                 ss >> mapValue;
1165                 _ssExtra = std::vector<char>(ss.begin(), ss.end());
1166             }
1167             ReadOrderPos(nOrderPos, mapValue);
1168         }
1169         if (std::string::npos != nSepPos)
1170             strComment.erase(nSepPos);
1171
1172         mapValue.erase("n");
1173     }
1174
1175 private:
1176     std::vector<char> _ssExtra;
1177 };
1178
1179 #endif // BITCOIN_WALLET_WALLET_H
This page took 0.088911 seconds and 4 git commands to generate.