Fix immature balance caching issues
[novacoin.git] / src / wallet.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
7
8 #include <string>
9 #include <vector>
10
11 #include <stdlib.h>
12
13 #include "main.h"
14 #include "key.h"
15 #include "keystore.h"
16 #include "script.h"
17 #include "ui_interface.h"
18 #include "util.h"
19 #include "walletdb.h"
20
21 extern bool fWalletUnlockMintOnly;
22 extern bool fConfChange;
23 class CAccountingEntry;
24 class CWalletTx;
25 class CReserveKey;
26 class COutput;
27 class CCoinControl;
28
29 /** (client) version numbers for particular wallet features */
30 enum WalletFeature
31 {
32     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
33
34     FEATURE_WALLETCRYPT = 40000, // wallet encryption
35     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
36     FEATURE_LATEST = 60000
37 };
38
39 /** A key pool entry */
40 class CKeyPool
41 {
42 public:
43     int64 nTime;
44     CPubKey vchPubKey;
45
46     CKeyPool()
47     {
48         nTime = GetTime();
49     }
50
51     CKeyPool(const CPubKey& vchPubKeyIn)
52     {
53         nTime = GetTime();
54         vchPubKey = vchPubKeyIn;
55     }
56
57     IMPLEMENT_SERIALIZE
58     (
59         if (!(nType & SER_GETHASH))
60             READWRITE(nVersion);
61         READWRITE(nTime);
62         READWRITE(vchPubKey);
63     )
64 };
65
66 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
67  * and provides the ability to create new transactions.
68  */
69 class CWallet : public CCryptoKeyStore
70 {
71 private:
72     bool SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
73     bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl *coinControl=NULL) const;
74
75     CWalletDB *pwalletdbEncryption;
76
77     // the current wallet version: clients below this version are not able to load the wallet
78     int nWalletVersion;
79
80     // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
81     int nWalletMaxVersion;
82
83 public:
84     mutable CCriticalSection cs_wallet;
85
86     bool fFileBacked;
87     std::string strWalletFile;
88
89     std::set<int64> setKeyPool;
90     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
91
92
93     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
94     MasterKeyMap mapMasterKeys;
95     unsigned int nMasterKeyMaxID;
96
97     CWallet()
98     {
99         nWalletVersion = FEATURE_BASE;
100         nWalletMaxVersion = FEATURE_BASE;
101         fFileBacked = false;
102         nMasterKeyMaxID = 0;
103         pwalletdbEncryption = NULL;
104         nOrderPosNext = 0;
105     }
106     CWallet(std::string strWalletFileIn)
107     {
108         nWalletVersion = FEATURE_BASE;
109         nWalletMaxVersion = FEATURE_BASE;
110         strWalletFile = strWalletFileIn;
111         fFileBacked = true;
112         nMasterKeyMaxID = 0;
113         pwalletdbEncryption = NULL;
114         nOrderPosNext = 0;
115     }
116
117     std::map<uint256, CWalletTx> mapWallet;
118     int64 nOrderPosNext;
119     std::map<uint256, int> mapRequestCount;
120
121     std::map<CTxDestination, std::string> mapAddressBook;
122
123     CPubKey vchDefaultKey;
124     int64 nTimeFirstKey;
125
126     // check whether we are allowed to upgrade (or already support) to the named feature
127     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
128
129     void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const;
130     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
131     bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
132     // keystore implementation
133     // Generate a new key
134     CPubKey GenerateNewKey();
135     // Adds a key to the store, and saves it to disk.
136     bool AddKey(const CKey& key);
137     // Adds a key to the store, without saving it to disk (used by LoadWallet)
138     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
139     // Load metadata (used by LoadWallet)
140     bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
141
142     bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
143
144     // Adds an encrypted key to the store, and saves it to disk.
145     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
146     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
147     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
148     bool AddCScript(const CScript& redeemScript);
149     bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
150
151     // Adds a watch-only address to the store, and saves it to disk.
152     bool AddWatchOnly(const CScript &dest);
153     // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
154     bool LoadWatchOnly(const CScript &dest);
155
156     bool Unlock(const SecureString& strWalletPassphrase);
157     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
158     bool EncryptWallet(const SecureString& strWalletPassphrase);
159
160     void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
161
162
163     /** Increment the next transaction order id
164         @return next transaction order id
165      */
166     int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
167
168     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
169     typedef std::multimap<int64, TxPair > TxItems;
170
171     /** Get the wallet's activity log
172         @return multimap of ordered transactions and accounting entries
173         @warning Returned pointers are *only* valid within the scope of passed acentries
174      */
175     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
176
177     void MarkDirty();
178     bool AddToWallet(const CWalletTx& wtxIn);
179     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
180     bool EraseFromWallet(uint256 hash);
181     void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
182     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
183     int ScanForWalletTransaction(const uint256& hashTx);
184     void ReacceptWalletTransactions();
185     void ResendWalletTransactions();
186     int64 GetBalance() const;
187     int64 GetWatchOnlyBalance() const;
188     int64 GetUnconfirmedBalance() const;
189     int64 GetUnconfirmedWatchOnlyBalance() const;
190     int64 GetImmatureBalance() const;
191     int64 GetImmatureWatchOnlyBalance() const;
192     int64 GetStake() const;
193     int64 GetNewMint() const;
194     int64 GetWatchOnlyStake() const;
195     int64 GetWatchOnlyNewMint() const;
196     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
197     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
198     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
199
200     bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
201     void GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight);
202     bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
203
204     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
205     std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
206
207     bool NewKeyPool();
208     bool TopUpKeyPool(unsigned int nSize = 0);
209     int64 AddReserveKey(const CKeyPool& keypool);
210     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
211     void KeepKey(int64 nIndex);
212     void ReturnKey(int64 nIndex);
213     bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
214     int64 GetOldestKeyPoolTime();
215     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
216
217     std::set< std::set<CTxDestination> > GetAddressGroupings();
218     std::map<CTxDestination, int64> GetAddressBalances();
219
220     isminetype IsMine(const CTxIn& txin) const;
221     int64 GetDebit(const CTxIn& txin, const isminefilter& filter) const;
222     isminetype IsMine(const CTxOut& txout) const
223     {
224         return ::IsMine(*this, txout.scriptPubKey);
225     }
226     int64 GetCredit(const CTxOut& txout, const isminefilter& filter) const
227     {
228         if (!MoneyRange(txout.nValue))
229             throw std::runtime_error("CWallet::GetCredit() : value out of range");
230         return (IsMine(txout) & filter ? txout.nValue : 0);
231     }
232     bool IsChange(const CTxOut& txout) const;
233     int64 GetChange(const CTxOut& txout) const
234     {
235         if (!MoneyRange(txout.nValue))
236             throw std::runtime_error("CWallet::GetChange() : value out of range");
237         return (IsChange(txout) ? txout.nValue : 0);
238     }
239     bool IsMine(const CTransaction& tx) const
240     {
241         BOOST_FOREACH(const CTxOut& txout, tx.vout)
242             if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
243                 return true;
244         return false;
245     }
246     bool IsFromMe(const CTransaction& tx) const
247     {
248         return (GetDebit(tx, MINE_ALL) > 0);
249     }
250     int64 GetDebit(const CTransaction& tx, const isminefilter& filter) const
251     {
252         int64 nDebit = 0;
253         BOOST_FOREACH(const CTxIn& txin, tx.vin)
254         {
255             nDebit += GetDebit(txin, filter);
256             if (!MoneyRange(nDebit))
257                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
258         }
259         return nDebit;
260     }
261     int64 GetCredit(const CTransaction& tx, const isminefilter& filter) const
262     {
263         int64 nCredit = 0;
264         BOOST_FOREACH(const CTxOut& txout, tx.vout)
265         {
266             nCredit += GetCredit(txout, filter);
267             if (!MoneyRange(nCredit))
268                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
269         }
270         return nCredit;
271     }
272     int64 GetChange(const CTransaction& tx) const
273     {
274         int64 nChange = 0;
275         BOOST_FOREACH(const CTxOut& txout, tx.vout)
276         {
277             nChange += GetChange(txout);
278             if (!MoneyRange(nChange))
279                 throw std::runtime_error("CWallet::GetChange() : value out of range");
280         }
281         return nChange;
282     }
283     void SetBestChain(const CBlockLocator& loc);
284
285     DBErrors LoadWallet(bool& fFirstRunRet);
286
287     bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
288
289     bool DelAddressBookName(const CTxDestination& address);
290
291     void UpdatedTransaction(const uint256 &hashTx);
292
293     void PrintWallet(const CBlock& block);
294
295     void Inventory(const uint256 &hash)
296     {
297         {
298             LOCK(cs_wallet);
299             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
300             if (mi != mapRequestCount.end())
301                 (*mi).second++;
302         }
303     }
304
305     unsigned int GetKeyPoolSize()
306     {
307         return setKeyPool.size();
308     }
309
310     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
311
312     bool SetDefaultKey(const CPubKey &vchPubKey);
313
314     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
315     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
316
317     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
318     bool SetMaxVersion(int nVersion);
319
320     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
321     int GetVersion() { return nWalletVersion; }
322
323     void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
324     void DisableTransaction(const CTransaction &tx);
325
326     /** Address book entry changed.
327      * @note called with lock cs_wallet held.
328      */
329     boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
330
331     /** Wallet transaction added, removed or updated.
332      * @note called with lock cs_wallet held.
333      */
334     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
335 };
336
337 /** A key allocated from the key pool. */
338 class CReserveKey
339 {
340 protected:
341     CWallet* pwallet;
342     int64 nIndex;
343     CPubKey vchPubKey;
344 public:
345     CReserveKey(CWallet* pwalletIn)
346     {
347         nIndex = -1;
348         pwallet = pwalletIn;
349     }
350
351     ~CReserveKey()
352     {
353         if (!fShutdown)
354             ReturnKey();
355     }
356
357     void ReturnKey();
358     CPubKey GetReservedKey();
359     void KeepKey();
360 };
361
362
363 typedef std::map<std::string, std::string> mapValue_t;
364
365
366 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
367 {
368     if (!mapValue.count("n"))
369     {
370         nOrderPos = -1; // TODO: calculate elsewhere
371         return;
372     }
373     nOrderPos = atoi64(mapValue["n"].c_str());
374 }
375
376
377 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
378 {
379     if (nOrderPos == -1)
380         return;
381     mapValue["n"] = i64tostr(nOrderPos);
382 }
383
384
385 /** A transaction with a bunch of additional info that only the owner cares about.
386  * It includes any unrecorded transactions needed to link it back to the block chain.
387  */
388 class CWalletTx : public CMerkleTx
389 {
390 private:
391     const CWallet* pwallet;
392
393 public:
394     std::vector<CMerkleTx> vtxPrev;
395     mapValue_t mapValue;
396     std::vector<std::pair<std::string, std::string> > vOrderForm;
397     unsigned int fTimeReceivedIsTxTime;
398     unsigned int nTimeReceived;  // time received by this node
399     unsigned int nTimeSmart;
400     char fFromMe;
401     std::string strFromAccount;
402     std::vector<char> vfSpent; // which outputs are already spent
403     int64 nOrderPos;  // position in ordered transaction list
404
405     // memory only
406     mutable bool fDebitCached;
407     mutable bool fWatchDebitCached;
408     mutable bool fCreditCached;
409     mutable bool fWatchCreditCached;
410     mutable bool fAvailableCreditCached;
411     mutable bool fImmatureCreditCached;
412     mutable bool fImmatureWatchCreditCached;
413     mutable bool fAvailableWatchCreditCached;
414     mutable bool fChangeCached;
415     mutable int64 nDebitCached;
416     mutable int64 nWatchDebitCached;
417     mutable int64 nCreditCached;
418     mutable int64 nWatchCreditCached;
419     mutable int64 nAvailableCreditCached;
420     mutable int64 nImmatureCreditCached;
421     mutable int64 nImmatureWatchCreditCached;
422     mutable int64 nAvailableWatchCreditCached;
423     mutable int64 nChangeCached;
424
425     CWalletTx()
426     {
427         Init(NULL);
428     }
429
430     CWalletTx(const CWallet* pwalletIn)
431     {
432         Init(pwalletIn);
433     }
434
435     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
436     {
437         Init(pwalletIn);
438     }
439
440     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
441     {
442         Init(pwalletIn);
443     }
444
445     void Init(const CWallet* pwalletIn)
446     {
447         pwallet = pwalletIn;
448         vtxPrev.clear();
449         mapValue.clear();
450         vOrderForm.clear();
451         fTimeReceivedIsTxTime = false;
452         nTimeReceived = 0;
453         nTimeSmart = 0;
454         fFromMe = false;
455         strFromAccount.clear();
456         vfSpent.clear();
457         fDebitCached = false;
458         fWatchDebitCached = false;
459         fCreditCached = false;
460         fWatchCreditCached = false;
461         fAvailableCreditCached = false;
462         fAvailableWatchCreditCached = false;
463         fImmatureCreditCached = false;
464         fImmatureWatchCreditCached = false;
465         fChangeCached = false;
466         nDebitCached = 0;
467         nWatchDebitCached = 0;
468         nCreditCached = 0;
469         nWatchCreditCached = 0;
470         nAvailableCreditCached = 0;
471         nAvailableWatchCreditCached = 0;
472         nImmatureCreditCached = 0;
473         nImmatureWatchCreditCached = 0;
474         nChangeCached = 0;
475         nOrderPos = -1;
476     }
477
478     IMPLEMENT_SERIALIZE
479     (
480         CWalletTx* pthis = const_cast<CWalletTx*>(this);
481         if (fRead)
482             pthis->Init(NULL);
483         char fSpent = false;
484
485         if (!fRead)
486         {
487             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
488
489             std::string str;
490             BOOST_FOREACH(char f, vfSpent)
491             {
492                 str += (f ? '1' : '0');
493                 if (f)
494                     fSpent = true;
495             }
496             pthis->mapValue["spent"] = str;
497
498             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
499
500             if (nTimeSmart)
501                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
502         }
503
504         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
505         READWRITE(vtxPrev);
506         READWRITE(mapValue);
507         READWRITE(vOrderForm);
508         READWRITE(fTimeReceivedIsTxTime);
509         READWRITE(nTimeReceived);
510         READWRITE(fFromMe);
511         READWRITE(fSpent);
512
513         if (fRead)
514         {
515             pthis->strFromAccount = pthis->mapValue["fromaccount"];
516
517             if (mapValue.count("spent"))
518                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
519                     pthis->vfSpent.push_back(c != '0');
520             else
521                 pthis->vfSpent.assign(vout.size(), fSpent);
522
523             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
524
525             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
526         }
527
528         pthis->mapValue.erase("fromaccount");
529         pthis->mapValue.erase("version");
530         pthis->mapValue.erase("spent");
531         pthis->mapValue.erase("n");
532         pthis->mapValue.erase("timesmart");
533     )
534
535     // marks certain txout's as spent
536     // returns true if any update took place
537     bool UpdateSpent(const std::vector<char>& vfNewSpent)
538     {
539         bool fReturn = false;
540         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
541         {
542             if (i == vfSpent.size())
543                 break;
544
545             if (vfNewSpent[i] && !vfSpent[i])
546             {
547                 vfSpent[i] = true;
548                 fReturn = true;
549                 fAvailableCreditCached = fAvailableWatchCreditCached = false;
550             }
551         }
552         return fReturn;
553     }
554
555     // make sure balances are recalculated
556     void MarkDirty()
557     {
558         fCreditCached = false;
559         fAvailableCreditCached = fAvailableWatchCreditCached = false;
560         fDebitCached = fWatchDebitCached = false;
561         fChangeCached = false;
562     }
563
564     void BindWallet(CWallet *pwalletIn)
565     {
566         pwallet = pwalletIn;
567         MarkDirty();
568     }
569
570     void MarkSpent(unsigned int nOut)
571     {
572         if (nOut >= vout.size())
573             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
574         vfSpent.resize(vout.size());
575         if (!vfSpent[nOut])
576         {
577             vfSpent[nOut] = true;
578             fAvailableCreditCached = fAvailableWatchCreditCached = false;
579         }
580     }
581
582     void MarkUnspent(unsigned int nOut)
583     {
584         if (nOut >= vout.size())
585             throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
586         vfSpent.resize(vout.size());
587         if (vfSpent[nOut])
588         {
589             vfSpent[nOut] = false;
590             fAvailableCreditCached = fAvailableWatchCreditCached = false;
591         }
592     }
593
594     bool IsSpent(unsigned int nOut) const
595     {
596         if (nOut >= vout.size())
597             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
598         if (nOut >= vfSpent.size())
599             return false;
600         return (!!vfSpent[nOut]);
601     }
602
603     int64 GetDebit(const isminefilter& filter) const
604     {
605         if (vin.empty())
606             return 0;
607
608         int64 nDebit = 0;
609         if (filter & MINE_SPENDABLE)
610         {
611             if (fDebitCached)
612                 nDebit += nDebitCached;
613             else
614             {
615                 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
616                 fDebitCached = true;
617                 nDebit += nDebitCached;
618             }
619         }
620         if (filter & MINE_WATCH_ONLY)
621         {
622             if (fWatchDebitCached)
623                 nDebit += nWatchDebitCached;
624             else
625             {
626                 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
627                 fWatchDebitCached = true;
628                 nDebit += nWatchDebitCached;
629             }
630         }
631
632         return nDebit;
633     }
634
635     int64 GetCredit(bool fUseCache=true) const
636     {
637         // Must wait until coinbase is safely deep enough in the chain before valuing it
638         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
639             return 0;
640
641         // GetBalance can assume transactions in mapWallet won't change
642         if (fUseCache) {
643             if (fCreditCached)
644                 return nCreditCached;
645         }
646
647         nCreditCached = pwallet->GetCredit(*this, MINE_ALL);
648         fCreditCached = true;
649
650         return nCreditCached;
651     }
652
653     int64 GetImmatureCredit(bool fUseCache=true) const
654     {
655         if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
656         {
657             if (fUseCache && fImmatureCreditCached)
658                 return nImmatureCreditCached;
659             nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
660             fImmatureCreditCached = true;
661             return nImmatureCreditCached;
662         }
663
664         return 0;
665     }
666
667     int64 GetImmatureWatchOnlyCredit(bool fUseCache=true) const
668     {
669         if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
670         {
671             if (fUseCache && fImmatureWatchCreditCached)
672                 return nImmatureWatchCreditCached;
673             nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
674             fImmatureWatchCreditCached = true;
675             return nImmatureWatchCreditCached;
676         }
677
678         return 0;
679     }
680
681
682     int64 GetAvailableCredit(bool fUseCache=true) const
683     {
684         // Must wait until coinbase is safely deep enough in the chain before valuing it
685         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
686             return 0;
687
688         if (fUseCache) {
689             if (fAvailableCreditCached)
690                 return nAvailableCreditCached;
691         }
692
693         int64 nCredit = 0;
694         for (unsigned int i = 0; i < vout.size(); i++)
695         {
696             if (!IsSpent(i))
697             {
698                 const CTxOut &txout = vout[i];
699                 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
700                 if (!MoneyRange(nCredit))
701                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
702             }
703         }
704
705         nAvailableCreditCached = nCredit;
706         fAvailableCreditCached = true;
707
708         return nCredit;
709     }
710
711     int64 GetAvailableWatchCredit(bool fUseCache=true) const
712     {
713         // Must wait until coinbase is safely deep enough in the chain before valuing it
714         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
715             return 0;
716
717         if (fUseCache) {
718             if (fAvailableWatchCreditCached)
719                 return nAvailableWatchCreditCached;
720         }
721
722         int64 nCredit = 0;
723         for (unsigned int i = 0; i < vout.size(); i++)
724         {
725             if (!IsSpent(i))
726             {
727                 const CTxOut &txout = vout[i];
728                 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
729                 if (!MoneyRange(nCredit))
730                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
731             }
732         }
733
734         nAvailableWatchCreditCached = nCredit;
735         fAvailableWatchCreditCached = true;
736
737         return nCredit;
738     }
739
740     int64 GetChange() const
741     {
742         if (fChangeCached)
743             return nChangeCached;
744         nChangeCached = pwallet->GetChange(*this);
745         fChangeCached = true;
746         return nChangeCached;
747     }
748
749     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
750                     std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount, const isminefilter& filter) const;
751
752     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
753                            int64& nSent, int64& nFee, const isminefilter& filter) const;
754
755     bool IsFromMe(const isminefilter& filter) const
756     {
757         return (GetDebit(filter) > 0);
758     }
759
760     bool IsTrusted() const
761     {
762         // Quick answer in most cases
763         if (!IsFinal())
764             return false;
765         if (GetDepthInMainChain() >= 1)
766             return true;
767         if (fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
768             return false;
769
770         // If no confirmations but it's from us, we can still
771         // consider it confirmed if all dependencies are confirmed
772         std::map<uint256, const CMerkleTx*> mapPrev;
773         std::vector<const CMerkleTx*> vWorkQueue;
774         vWorkQueue.reserve(vtxPrev.size()+1);
775         vWorkQueue.push_back(this);
776         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
777         {
778             const CMerkleTx* ptx = vWorkQueue[i];
779
780             if (!ptx->IsFinal())
781                 return false;
782             if (ptx->GetDepthInMainChain() >= 1)
783                 continue;
784             if (!pwallet->IsFromMe(*ptx))
785                 return false;
786
787             if (mapPrev.empty())
788             {
789                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
790                     mapPrev[tx.GetHash()] = &tx;
791             }
792
793             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
794             {
795                 if (!mapPrev.count(txin.prevout.hash))
796                     return false;
797                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
798             }
799         }
800
801         return true;
802     }
803
804     bool WriteToDisk();
805
806     int64 GetTxTime() const;
807     int GetRequestCount() const;
808
809     void AddSupportingTransactions(CTxDB& txdb);
810
811     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
812     bool AcceptWalletTransaction();
813
814     void RelayWalletTransaction(CTxDB& txdb);
815     void RelayWalletTransaction();
816 };
817
818
819
820
821 class COutput
822 {
823 public:
824     const CWalletTx *tx;
825     int i;
826     int nDepth;
827     bool fSpendable;
828
829     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
830     {
831         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
832     }
833
834     std::string ToString() const
835     {
836         return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
837     }
838
839     void print() const
840     {
841         printf("%s\n", ToString().c_str());
842     }
843 };
844
845
846
847
848 /** Private key that includes an expiration date in case it never gets used. */
849 class CWalletKey
850 {
851 public:
852     CPrivKey vchPrivKey;
853     int64 nTimeCreated;
854     int64 nTimeExpires;
855     std::string strComment;
856     //// todo: add something to note what created it (user, getnewaddress, change)
857     ////   maybe should have a map<string, string> property map
858
859     CWalletKey(int64 nExpires=0)
860     {
861         nTimeCreated = (nExpires ? GetTime() : 0);
862         nTimeExpires = nExpires;
863     }
864
865     IMPLEMENT_SERIALIZE
866     (
867         if (!(nType & SER_GETHASH))
868             READWRITE(nVersion);
869         READWRITE(vchPrivKey);
870         READWRITE(nTimeCreated);
871         READWRITE(nTimeExpires);
872         READWRITE(strComment);
873     )
874 };
875
876
877
878
879
880
881 /** Account information.
882  * Stored in wallet with key "acc"+string account name.
883  */
884 class CAccount
885 {
886 public:
887     CPubKey vchPubKey;
888
889     CAccount()
890     {
891         SetNull();
892     }
893
894     void SetNull()
895     {
896         vchPubKey = CPubKey();
897     }
898
899     IMPLEMENT_SERIALIZE
900     (
901         if (!(nType & SER_GETHASH))
902             READWRITE(nVersion);
903         READWRITE(vchPubKey);
904     )
905 };
906
907
908
909 /** Internal transfers.
910  * Database key is acentry<account><counter>.
911  */
912 class CAccountingEntry
913 {
914 public:
915     std::string strAccount;
916     int64 nCreditDebit;
917     int64 nTime;
918     std::string strOtherAccount;
919     std::string strComment;
920     mapValue_t mapValue;
921     int64 nOrderPos;  // position in ordered transaction list
922     uint64 nEntryNo;
923
924     CAccountingEntry()
925     {
926         SetNull();
927     }
928
929     void SetNull()
930     {
931         nCreditDebit = 0;
932         nTime = 0;
933         strAccount.clear();
934         strOtherAccount.clear();
935         strComment.clear();
936         nOrderPos = -1;
937     }
938
939     IMPLEMENT_SERIALIZE
940     (
941         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
942         if (!(nType & SER_GETHASH))
943             READWRITE(nVersion);
944         // Note: strAccount is serialized as part of the key, not here.
945         READWRITE(nCreditDebit);
946         READWRITE(nTime);
947         READWRITE(strOtherAccount);
948
949         if (!fRead)
950         {
951             WriteOrderPos(nOrderPos, me.mapValue);
952
953             if (!(mapValue.empty() && _ssExtra.empty()))
954             {
955                 CDataStream ss(nType, nVersion);
956                 ss.insert(ss.begin(), '\0');
957                 ss << mapValue;
958                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
959                 me.strComment.append(ss.str());
960             }
961         }
962
963         READWRITE(strComment);
964
965         size_t nSepPos = strComment.find("\0", 0, 1);
966         if (fRead)
967         {
968             me.mapValue.clear();
969             if (std::string::npos != nSepPos)
970             {
971                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
972                 ss >> me.mapValue;
973                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
974             }
975             ReadOrderPos(me.nOrderPos, me.mapValue);
976         }
977         if (std::string::npos != nSepPos)
978             me.strComment.erase(nSepPos);
979
980         me.mapValue.erase("n");
981     )
982
983 private:
984     std::vector<char> _ssExtra;
985 };
986
987 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
988
989 #endif