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