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