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