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