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