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