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