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