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