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