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