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