]> Git Repo - VerusCoin.git/blob - src/wallet/wallet.h
Test
[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 "key.h"
12 #include "keystore.h"
13 #include "main.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 #define _COINBASE_MATURITY 100
62 static const unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10;
63
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 /** A note outpoint */
157 class JSOutPoint
158 {
159 public:
160     // Transaction hash
161     uint256 hash;
162     // Index into CTransaction.vjoinsplit
163 #ifdef __LP64__
164     uint64_t js;
165 #else
166     size_t js;
167 #endif
168     // Index into JSDescription fields of length ZC_NUM_JS_OUTPUTS
169     uint8_t n;
170
171     JSOutPoint() { SetNull(); }
172     JSOutPoint(uint256 h, size_t js, uint8_t n) : hash {h}, js {js}, n {n} { }
173
174     ADD_SERIALIZE_METHODS;
175
176     template <typename Stream, typename Operation>
177     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
178         READWRITE(hash);
179         READWRITE(js);
180         READWRITE(n);
181     }
182
183     void SetNull() { hash.SetNull(); }
184     bool IsNull() const { return hash.IsNull(); }
185
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));
190     }
191
192     friend bool operator==(const JSOutPoint& a, const JSOutPoint& b) {
193         return (a.hash == b.hash && a.js == b.js && a.n == b.n);
194     }
195
196     friend bool operator!=(const JSOutPoint& a, const JSOutPoint& b) {
197         return !(a == b);
198     }
199
200     std::string ToString() const;
201 };
202
203 class CNoteData
204 {
205 public:
206     libzcash::PaymentAddress address;
207
208     /**
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.
212      *
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.
219      */
220     boost::optional<uint256> nullifier;
221
222     /**
223      * Cached incremental witnesses for spendable Notes.
224      * Beginning of the list is the most recent witness.
225      */
226     std::list<ZCIncrementalWitness> witnesses;
227
228     /**
229      * Block height corresponding to the most current witness.
230      *
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.
236      */
237     int witnessHeight;
238
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} { }
244
245     ADD_SERIALIZE_METHODS;
246
247     template <typename Stream, typename Operation>
248     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
249         READWRITE(address);
250         READWRITE(nullifier);
251         READWRITE(witnesses);
252         READWRITE(witnessHeight);
253     }
254
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));
258     }
259
260     friend bool operator==(const CNoteData& a, const CNoteData& b) {
261         return (a.address == b.address && a.nullifier == b.nullifier);
262     }
263
264     friend bool operator!=(const CNoteData& a, const CNoteData& b) {
265         return !(a == b);
266     }
267 };
268
269 typedef std::map<JSOutPoint, CNoteData> mapNoteData_t;
270
271 /** Decrypted note and its location in a transaction. */
272 struct CNotePlaintextEntry
273 {
274     JSOutPoint jsop;
275     libzcash::PaymentAddress address;
276     libzcash::NotePlaintext plaintext;
277 };
278
279
280
281 /** A transaction with a merkle branch linking it to the block chain. */
282 class CMerkleTx : public CTransaction
283 {
284 private:
285     int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
286
287 public:
288     uint256 hashBlock;
289     std::vector<uint256> vMerkleBranch;
290     int nIndex;
291
292     // memory only
293     mutable bool fMerkleVerified;
294
295
296     CMerkleTx()
297     {
298         Init();
299     }
300
301     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
302     {
303         Init();
304     }
305
306     void Init()
307     {
308         hashBlock = uint256();
309         nIndex = -1;
310         fMerkleVerified = false;
311     }
312
313     ADD_SERIALIZE_METHODS;
314
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);
321         READWRITE(nIndex);
322     }
323
324     int SetMerkleBranch(const CBlock& block);
325
326
327     /**
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
332      */
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);
338 };
339
340 /**
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.
343  */
344 class CWalletTx : public CMerkleTx
345 {
346 private:
347     const CWallet* pwallet;
348
349 public:
350     mapValue_t mapValue;
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;
356     char fFromMe;
357     std::string strFromAccount;
358     int64_t nOrderPos; //! position in ordered transaction list
359
360     // memory only
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;
379
380     CWalletTx()
381     {
382         Init(NULL);
383     }
384
385     CWalletTx(const CWallet* pwalletIn)
386     {
387         Init(pwalletIn);
388     }
389
390     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
391     {
392         Init(pwalletIn);
393     }
394
395     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
396     {
397         Init(pwalletIn);
398     }
399
400     void Init(const CWallet* pwalletIn)
401     {
402         pwallet = pwalletIn;
403         mapValue.clear();
404         mapNoteData.clear();
405         vOrderForm.clear();
406         fTimeReceivedIsTxTime = false;
407         nTimeReceived = 0;
408         nTimeSmart = 0;
409         fFromMe = 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;
420         nDebitCached = 0;
421         nCreditCached = 0;
422         nImmatureCreditCached = 0;
423         nAvailableCreditCached = 0;
424         nWatchDebitCached = 0;
425         nWatchCreditCached = 0;
426         nAvailableWatchCreditCached = 0;
427         nImmatureWatchCreditCached = 0;
428         nChangeCached = 0;
429         nOrderPos = -1;
430     }
431
432     ADD_SERIALIZE_METHODS;
433
434     template <typename Stream, typename Operation>
435     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
436         if (ser_action.ForRead())
437             Init(NULL);
438         char fSpent = false;
439
440         if (!ser_action.ForRead())
441         {
442             mapValue["fromaccount"] = strFromAccount;
443
444             WriteOrderPos(nOrderPos, mapValue);
445
446             if (nTimeSmart)
447                 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
448         }
449
450         READWRITE(*(CMerkleTx*)this);
451         std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
452         READWRITE(vUnused);
453         READWRITE(mapValue);
454         READWRITE(mapNoteData);
455         READWRITE(vOrderForm);
456         READWRITE(fTimeReceivedIsTxTime);
457         READWRITE(nTimeReceived);
458         READWRITE(fFromMe);
459         READWRITE(fSpent);
460
461         if (ser_action.ForRead())
462         {
463             strFromAccount = mapValue["fromaccount"];
464
465             ReadOrderPos(nOrderPos, mapValue);
466
467             nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
468         }
469
470         mapValue.erase("fromaccount");
471         mapValue.erase("version");
472         mapValue.erase("spent");
473         mapValue.erase("n");
474         mapValue.erase("timesmart");
475     }
476
477     //! make sure balances are recalculated
478     void MarkDirty()
479     {
480         fCreditCached = false;
481         fAvailableCreditCached = false;
482         fWatchDebitCached = false;
483         fWatchCreditCached = false;
484         fAvailableWatchCreditCached = false;
485         fImmatureWatchCreditCached = false;
486         fDebitCached = false;
487         fChangeCached = false;
488     }
489
490     void BindWallet(CWallet *pwalletIn)
491     {
492         pwallet = pwalletIn;
493         MarkDirty();
494     }
495
496     void SetNoteData(mapNoteData_t &noteData);
497
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;
506
507     void GetAmounts(std::list<COutputEntry>& listReceived,
508                     std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
509
510     void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
511                            CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
512
513     bool IsFromMe(const isminefilter& filter) const
514     {
515         return (GetDebit(filter) > 0);
516     }
517
518     bool IsTrusted() const;
519
520     bool WriteToDisk(CWalletDB *pwalletdb);
521
522     int64_t GetTxTime() const;
523     int GetRequestCount() const;
524
525     bool RelayWalletTransaction();
526
527     std::set<uint256> GetConflicts() const;
528 };
529
530
531
532
533 class COutput
534 {
535 public:
536     const CWalletTx *tx;
537     int i;
538     int nDepth;
539     bool fSpendable;
540
541     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
542     {
543         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
544     }
545
546     std::string ToString() const;
547 };
548
549
550
551
552 /** Private key that includes an expiration date in case it never gets used. */
553 class CWalletKey
554 {
555 public:
556     CPrivKey vchPrivKey;
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
562
563     CWalletKey(int64_t nExpires=0);
564
565     ADD_SERIALIZE_METHODS;
566
567     template <typename Stream, typename Operation>
568     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
569         if (!(nType & SER_GETHASH))
570             READWRITE(nVersion);
571         READWRITE(vchPrivKey);
572         READWRITE(nTimeCreated);
573         READWRITE(nTimeExpires);
574         READWRITE(LIMITED_STRING(strComment, 65536));
575     }
576 };
577
578 /**
579  * Internal transfers.
580  * Database key is acentry<account><counter>.
581  */
582 class CAccountingEntry
583 {
584 public:
585     std::string strAccount;
586     CAmount nCreditDebit;
587     int64_t nTime;
588     std::string strOtherAccount;
589     std::string strComment;
590     mapValue_t mapValue;
591     int64_t nOrderPos;  //! position in ordered transaction list
592     uint64_t nEntryNo;
593
594     CAccountingEntry()
595     {
596         SetNull();
597     }
598
599     void SetNull()
600     {
601         nCreditDebit = 0;
602         nTime = 0;
603         strAccount.clear();
604         strOtherAccount.clear();
605         strComment.clear();
606         nOrderPos = -1;
607         nEntryNo = 0;
608     }
609
610     ADD_SERIALIZE_METHODS;
611
612     template <typename Stream, typename Operation>
613     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
614         if (!(nType & SER_GETHASH))
615             READWRITE(nVersion);
616         //! Note: strAccount is serialized as part of the key, not here.
617         READWRITE(nCreditDebit);
618         READWRITE(nTime);
619         READWRITE(LIMITED_STRING(strOtherAccount, 65536));
620
621         if (!ser_action.ForRead())
622         {
623             WriteOrderPos(nOrderPos, mapValue);
624
625             if (!(mapValue.empty() && _ssExtra.empty()))
626             {
627                 CDataStream ss(nType, nVersion);
628                 ss.insert(ss.begin(), '\0');
629                 ss << mapValue;
630                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
631                 strComment.append(ss.str());
632             }
633         }
634
635         READWRITE(LIMITED_STRING(strComment, 65536));
636
637         size_t nSepPos = strComment.find("\0", 0, 1);
638         if (ser_action.ForRead())
639         {
640             mapValue.clear();
641             if (std::string::npos != nSepPos)
642             {
643                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
644                 ss >> mapValue;
645                 _ssExtra = std::vector<char>(ss.begin(), ss.end());
646             }
647             ReadOrderPos(nOrderPos, mapValue);
648         }
649         if (std::string::npos != nSepPos)
650             strComment.erase(nSepPos);
651
652         mapValue.erase("n");
653     }
654
655 private:
656     std::vector<char> _ssExtra;
657 };
658
659
660 /**
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.
663  */
664 class CWallet : public CCryptoKeyStore, public CValidationInterface
665 {
666 private:
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;
668
669     CWalletDB *pwalletdbEncryption;
670
671     //! the current wallet version: clients below this version are not able to load the wallet
672     int nWalletVersion;
673
674     //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
675     int nWalletMaxVersion;
676
677     int64_t nNextResend;
678     int64_t nLastResend;
679     bool fBroadcastTransactions;
680
681     template <class T>
682     using TxSpendMap = std::multimap<T, uint256>;
683     /**
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).
687      */
688     typedef TxSpendMap<COutPoint> TxSpends;
689     TxSpends mapTxSpends;
690     /**
691      * Used to keep track of spent Notes, and
692      * detect and report conflicts (double-spends).
693      */
694     typedef TxSpendMap<uint256> TxNullifiers;
695     TxNullifiers mapTxNullifiers;
696
697     void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
698     void AddToSpends(const uint256& nullifier, const uint256& wtxid);
699     void AddToSpends(const uint256& wtxid);
700
701 public:
702     /*
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.
706      */
707     int64_t nWitnessCacheSize;
708
709     void ClearNoteWitnessCache();
710
711 protected:
712     /**
713      * pindex is the new tip being connected.
714      */
715     void IncrementNoteWitnesses(const CBlockIndex* pindex,
716                                 const CBlock* pblock,
717                                 ZCIncrementalMerkleTree& tree);
718     /**
719      * pindex is the old tip being disconnected.
720      */
721     void DecrementNoteWitnesses(const CBlockIndex* pindex);
722
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");
728             return;
729         }
730         try {
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");
734                     walletdb.TxnAbort();
735                     return;
736                 }
737             }
738             if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
739                 LogPrintf("SetBestChain(): Failed to write nWitnessCacheSize, aborting atomic write\n");
740                 walletdb.TxnAbort();
741                 return;
742             }
743             if (!walletdb.WriteBestBlock(loc)) {
744                 LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
745                 walletdb.TxnAbort();
746                 return;
747             }
748         } catch (const std::exception &exc) {
749             // Unexpected failure
750             LogPrintf("SetBestChain(): Unexpected error during atomic write:\n");
751             LogPrintf("%s\n", exc.what());
752             walletdb.TxnAbort();
753             return;
754         }
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");
758             return;
759         }
760     }
761
762 private:
763     template <class T>
764     void SyncMetaData(std::pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator>);
765
766 protected:
767     bool UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx);
768     void MarkAffectedTransactionsDirty(const CTransaction& tx);
769
770 public:
771     /*
772      * Main wallet lock.
773      * This lock protects all the fields added by CWallet
774      *   except for:
775      *      fFileBacked (immutable after instantiation)
776      *      strWalletFile (immutable after instantiation)
777      */
778     mutable CCriticalSection cs_wallet;
779
780     bool fFileBacked;
781     std::string strWalletFile;
782
783     std::set<int64_t> setKeyPool;
784     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
785     std::map<libzcash::PaymentAddress, CKeyMetadata> mapZKeyMetadata;
786
787     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
788     MasterKeyMap mapMasterKeys;
789     unsigned int nMasterKeyMaxID;
790
791     CWallet()
792     {
793         SetNull();
794     }
795
796     CWallet(const std::string& strWalletFileIn)
797     {
798         SetNull();
799
800         strWalletFile = strWalletFileIn;
801         fFileBacked = true;
802     }
803
804     ~CWallet()
805     {
806         delete pwalletdbEncryption;
807         pwalletdbEncryption = NULL;
808     }
809
810     void SetNull()
811     {
812         nWalletVersion = FEATURE_BASE;
813         nWalletMaxVersion = FEATURE_BASE;
814         fFileBacked = false;
815         nMasterKeyMaxID = 0;
816         pwalletdbEncryption = NULL;
817         nOrderPosNext = 0;
818         nNextResend = 0;
819         nLastResend = 0;
820         nTimeFirstKey = 0;
821         fBroadcastTransactions = false;
822         nWitnessCacheSize = 0;
823     }
824
825     /**
826      * The reverse mapping of nullifiers to notes.
827      *
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:
831      *
832      * - Parent transactions can't be marked dirty when a child transaction that
833      *   spends their output notes is updated.
834      *
835      *   - We currently don't cache any note values, so this is not a problem,
836      *     yet.
837      *
838      * - GetFilteredNotes can't filter out spent notes.
839      *
840      *   - Per the comment in CNoteData, we assume that if we don't have a
841      *     cached nullifier, the note is not spent.
842      *
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:
846      *
847      * - We receive a note when the wallet is locked, and then spend it using a
848      *   different wallet client.
849      *
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.
853      *
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.
860      *
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:
867      *
868      * - Unlocking the wallet (to fill all nullifier caches).
869      *
870      * - Restarting the node with -reindex (which operates on a locked wallet
871      *   but with the now-cached nullifiers).
872      */
873     std::map<uint256, JSOutPoint> mapNullifiersToNotes;
874
875     std::map<uint256, CWalletTx> mapWallet;
876
877     int64_t nOrderPosNext;
878     std::map<uint256, int> mapRequestCount;
879
880     std::map<CTxDestination, CAddressBookData> mapAddressBook;
881
882     CPubKey vchDefaultKey;
883
884     std::set<COutPoint> setLockedCoins;
885     std::set<JSOutPoint> setLockedNotes;
886
887     int64_t nTimeFirstKey;
888
889     const CWalletTx* GetWalletTx(const uint256& hash) const;
890
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; }
893
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;
896
897     bool IsSpent(const uint256& hash, unsigned int n) const;
898     bool IsSpent(const uint256& nullifier) const;
899
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);
905
906
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();
912
913
914     /**
915      * keystore implementation
916      * Generate a new key
917      */
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);
925
926     bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
927
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);
934
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;
943
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);
949
950     bool Unlock(const SecureString& strWalletPassphrase);
951     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
952     bool EncryptWallet(const SecureString& strWalletPassphrase);
953
954     void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
955
956     /**
957       * ZKeys
958       */
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);
971
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);
977
978     /**
979      * Increment the next transaction order id
980      * @return next transaction order id
981      */
982     int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
983
984     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
985     typedef std::multimap<int64_t, TxPair > TxItems;
986
987     /**
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
991      */
992     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
993
994     void MarkDirty();
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);
1019
1020     static CFeeRate minTxFee;
1021     static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
1022
1023     bool NewKeyPool();
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;
1031
1032     std::set< std::set<CTxDestination> > GetAddressGroupings();
1033     std::map<CTxDestination, CAmount> GetAddressBalances();
1034
1035     std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
1036
1037     boost::optional<uint256> GetNoteNullifier(
1038         const JSDescription& jsdesc,
1039         const libzcash::PaymentAddress& address,
1040         const ZCNoteDecryption& dec,
1041         const uint256& hSig,
1042         uint8_t n) const;
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);
1049
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);
1065
1066     DBErrors LoadWallet(bool& fFirstRunRet);
1067     DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1068
1069     bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1070
1071     bool DelAddressBook(const CTxDestination& address);
1072
1073     void UpdatedTransaction(const uint256 &hashTx);
1074
1075     void Inventory(const uint256 &hash)
1076     {
1077         {
1078             LOCK(cs_wallet);
1079             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1080             if (mi != mapRequestCount.end())
1081                 (*mi).second++;
1082         }
1083     }
1084
1085     unsigned int GetKeyPoolSize()
1086     {
1087         AssertLockHeld(cs_wallet); // setKeyPool
1088         return setKeyPool.size();
1089     }
1090
1091     bool SetDefaultKey(const CPubKey &vchPubKey);
1092
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);
1095
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);
1098
1099     //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1100     int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1101
1102     //! Get wallet transactions that conflict with given transaction (spend same outputs)
1103     std::set<uint256> GetConflicts(const uint256& txid) const;
1104
1105     //! Flush wallet (bitdb flush)
1106     void Flush(bool shutdown=false);
1107
1108     //! Verify the wallet database and perform salvage if required
1109     static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
1110
1111     /**
1112      * Address book entry changed.
1113      * @note called with lock cs_wallet held.
1114      */
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;
1119
1120     /**
1121      * Wallet transaction added, removed or updated.
1122      * @note called with lock cs_wallet held.
1123      */
1124     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1125             ChangeType status)> NotifyTransactionChanged;
1126
1127     /** Show progress e.g. for rescan */
1128     boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1129
1130     /** Watch-only address added */
1131     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1132
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; }
1137
1138     /* Find notes filtered by payment address, min depth, ability to spend */
1139     void GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries,
1140                           std::string address,
1141                           int minDepth=1,
1142                           bool ignoreSpent=true,
1143                           bool ignoreUnspendable=true);
1144
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,
1148                           int minDepth=1,
1149                           bool ignoreSpent=true,
1150                           bool ignoreUnspendable=true);
1151     
1152 };
1153
1154 /** A key allocated from the key pool. */
1155 class CReserveKey
1156 {
1157 protected:
1158     CWallet* pwallet;
1159     int64_t nIndex;
1160     CPubKey vchPubKey;
1161 public:
1162     CReserveKey(CWallet* pwalletIn)
1163     {
1164         nIndex = -1;
1165         pwallet = pwalletIn;
1166     }
1167
1168     ~CReserveKey()
1169     {
1170         ReturnKey();
1171     }
1172
1173     void ReturnKey();
1174     virtual bool GetReservedKey(CPubKey &pubkey);
1175     void KeepKey();
1176 };
1177
1178
1179 /**
1180  * Account information.
1181  * Stored in wallet with key "acc"+string account name.
1182  */
1183 class CAccount
1184 {
1185 public:
1186     CPubKey vchPubKey;
1187
1188     CAccount()
1189     {
1190         SetNull();
1191     }
1192
1193     void SetNull()
1194     {
1195         vchPubKey = CPubKey();
1196     }
1197
1198     ADD_SERIALIZE_METHODS;
1199
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);
1205     }
1206 };
1207 #endif // BITCOIN_WALLET_WALLET_H
This page took 0.091024 seconds and 4 git commands to generate.