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