Keep address labels for pubkey pair addresses.
[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 AddMalleableKey(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 LoadMalleableKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
170     bool LoadCryptedMalleableKey(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 CBitcoinAddress& address, const std::string& strName);
323
324     bool DelAddressBookName(const CBitcoinAddress& address);
325
326     void UpdatedTransaction(const uint256 &hashTx);
327
328     void PrintWallet(const CBlock& block);
329
330     void Inventory(const uint256 &hash)
331     {
332         {
333             LOCK(cs_wallet);
334             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
335             if (mi != mapRequestCount.end())
336                 (*mi).second++;
337         }
338     }
339
340     unsigned int GetKeyPoolSize()
341     {
342         return (unsigned int)(setKeyPool.size());
343     }
344
345     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
346
347     bool SetDefaultKey(const CPubKey &vchPubKey);
348
349     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
350     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
351
352     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
353     bool SetMaxVersion(int nVersion);
354
355     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
356     int GetVersion() { return nWalletVersion; }
357
358     void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
359     void DisableTransaction(const CTransaction &tx);
360
361     /** Address book entry changed.
362      * @note called with lock cs_wallet held.
363      */
364     boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
365
366     /** Wallet transaction added, removed or updated.
367      * @note called with lock cs_wallet held.
368      */
369     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
370
371     /** Watch-only address added */
372     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
373 };
374
375 /** A key allocated from the key pool. */
376 class CReserveKey
377 {
378 protected:
379     CWallet* pwallet;
380     int64_t nIndex;
381     CPubKey vchPubKey;
382 public:
383     CReserveKey(CWallet* pwalletIn)
384     {
385         nIndex = -1;
386         pwallet = pwalletIn;
387     }
388
389     ~CReserveKey()
390     {
391         if (!fShutdown)
392             ReturnKey();
393     }
394
395     void ReturnKey();
396     CPubKey GetReservedKey();
397     void KeepKey();
398 };
399
400
401 typedef std::map<std::string, std::string> mapValue_t;
402
403
404 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
405 {
406     if (!mapValue.count("n"))
407     {
408         nOrderPos = -1; // TODO: calculate elsewhere
409         return;
410     }
411     nOrderPos = atoi64(mapValue["n"].c_str());
412 }
413
414
415 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
416 {
417     if (nOrderPos == -1)
418         return;
419     mapValue["n"] = i64tostr(nOrderPos);
420 }
421
422
423 /** A transaction with a bunch of additional info that only the owner cares about.
424  * It includes any unrecorded transactions needed to link it back to the block chain.
425  */
426 class CWalletTx : public CMerkleTx
427 {
428 private:
429     const CWallet* pwallet;
430
431 public:
432     std::vector<CMerkleTx> vtxPrev;
433     mapValue_t mapValue;
434     std::vector<std::pair<std::string, std::string> > vOrderForm;
435     unsigned int fTimeReceivedIsTxTime;
436     unsigned int nTimeReceived;  // time received by this node
437     unsigned int nTimeSmart;
438     char fFromMe;
439     std::string strFromAccount;
440     std::vector<char> vfSpent; // which outputs are already spent
441     int64_t nOrderPos;  // position in ordered transaction list
442
443     // memory only
444     mutable bool fDebitCached;
445     mutable bool fWatchDebitCached;
446     mutable bool fCreditCached;
447     mutable bool fWatchCreditCached;
448     mutable bool fAvailableCreditCached;
449     mutable bool fImmatureCreditCached;
450     mutable bool fImmatureWatchCreditCached;
451     mutable bool fAvailableWatchCreditCached;
452     mutable bool fChangeCached;
453     mutable int64_t nDebitCached;
454     mutable int64_t nWatchDebitCached;
455     mutable int64_t nCreditCached;
456     mutable int64_t nWatchCreditCached;
457     mutable int64_t nAvailableCreditCached;
458     mutable int64_t nImmatureCreditCached;
459     mutable int64_t nImmatureWatchCreditCached;
460     mutable int64_t nAvailableWatchCreditCached;
461     mutable int64_t nChangeCached;
462
463     CWalletTx()
464     {
465         Init(NULL);
466     }
467
468     CWalletTx(const CWallet* pwalletIn)
469     {
470         Init(pwalletIn);
471     }
472
473     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
474     {
475         Init(pwalletIn);
476     }
477
478     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
479     {
480         Init(pwalletIn);
481     }
482
483     void Init(const CWallet* pwalletIn)
484     {
485         pwallet = pwalletIn;
486         vtxPrev.clear();
487         mapValue.clear();
488         vOrderForm.clear();
489         fTimeReceivedIsTxTime = false;
490         nTimeReceived = 0;
491         nTimeSmart = 0;
492         fFromMe = false;
493         strFromAccount.clear();
494         vfSpent.clear();
495         fDebitCached = false;
496         fWatchDebitCached = false;
497         fCreditCached = false;
498         fWatchCreditCached = false;
499         fAvailableCreditCached = false;
500         fAvailableWatchCreditCached = false;
501         fImmatureCreditCached = false;
502         fImmatureWatchCreditCached = false;
503         fChangeCached = false;
504         nDebitCached = 0;
505         nWatchDebitCached = 0;
506         nCreditCached = 0;
507         nWatchCreditCached = 0;
508         nAvailableCreditCached = 0;
509         nAvailableWatchCreditCached = 0;
510         nImmatureCreditCached = 0;
511         nImmatureWatchCreditCached = 0;
512         nChangeCached = 0;
513         nOrderPos = -1;
514     }
515
516     IMPLEMENT_SERIALIZE
517     (
518         CWalletTx* pthis = const_cast<CWalletTx*>(this);
519         if (fRead)
520             pthis->Init(NULL);
521         char fSpent = false;
522
523         if (!fRead)
524         {
525             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
526
527             std::string str;
528             BOOST_FOREACH(char f, vfSpent)
529             {
530                 str += (f ? '1' : '0');
531                 if (f)
532                     fSpent = true;
533             }
534             pthis->mapValue["spent"] = str;
535
536             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
537
538             if (nTimeSmart)
539                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
540         }
541
542         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
543         READWRITE(vtxPrev);
544         READWRITE(mapValue);
545         READWRITE(vOrderForm);
546         READWRITE(fTimeReceivedIsTxTime);
547         READWRITE(nTimeReceived);
548         READWRITE(fFromMe);
549         READWRITE(fSpent);
550
551         if (fRead)
552         {
553             pthis->strFromAccount = pthis->mapValue["fromaccount"];
554
555             if (mapValue.count("spent"))
556                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
557                     pthis->vfSpent.push_back(c != '0');
558             else
559                 pthis->vfSpent.assign(vout.size(), fSpent);
560
561             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
562
563             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
564         }
565
566         pthis->mapValue.erase("fromaccount");
567         pthis->mapValue.erase("version");
568         pthis->mapValue.erase("spent");
569         pthis->mapValue.erase("n");
570         pthis->mapValue.erase("timesmart");
571     )
572
573     // marks certain txout's as spent
574     // returns true if any update took place
575     bool UpdateSpent(const std::vector<char>& vfNewSpent)
576     {
577         bool fReturn = false;
578         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
579         {
580             if (i == vfSpent.size())
581                 break;
582
583             if (vfNewSpent[i] && !vfSpent[i])
584             {
585                 vfSpent[i] = true;
586                 fReturn = true;
587                 fAvailableCreditCached = fAvailableWatchCreditCached = false;
588             }
589         }
590         return fReturn;
591     }
592
593     // make sure balances are recalculated
594     void MarkDirty()
595     {
596         fCreditCached = false;
597         fAvailableCreditCached = fAvailableWatchCreditCached = false;
598         fDebitCached = fWatchDebitCached = false;
599         fChangeCached = false;
600     }
601
602     void BindWallet(CWallet *pwalletIn)
603     {
604         pwallet = pwalletIn;
605         MarkDirty();
606     }
607
608     void MarkSpent(unsigned int nOut)
609     {
610         if (nOut >= vout.size())
611             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
612         vfSpent.resize(vout.size());
613         if (!vfSpent[nOut])
614         {
615             vfSpent[nOut] = true;
616             fAvailableCreditCached = fAvailableWatchCreditCached = false;
617         }
618     }
619
620     void MarkUnspent(unsigned int nOut)
621     {
622         if (nOut >= vout.size())
623             throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
624         vfSpent.resize(vout.size());
625         if (vfSpent[nOut])
626         {
627             vfSpent[nOut] = false;
628             fAvailableCreditCached = fAvailableWatchCreditCached = false;
629         }
630     }
631
632     bool IsSpent(unsigned int nOut) const
633     {
634         if (nOut >= vout.size())
635             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
636         if (nOut >= vfSpent.size())
637             return false;
638         return (!!vfSpent[nOut]);
639     }
640
641     int64_t GetDebit(const isminefilter& filter) const
642     {
643         if (vin.empty())
644             return 0;
645
646         int64_t nDebit = 0;
647         if (filter & MINE_SPENDABLE)
648         {
649             if (fDebitCached)
650                 nDebit += nDebitCached;
651             else
652             {
653                 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
654                 fDebitCached = true;
655                 nDebit += nDebitCached;
656             }
657         }
658         if (filter & MINE_WATCH_ONLY)
659         {
660             if (fWatchDebitCached)
661                 nDebit += nWatchDebitCached;
662             else
663             {
664                 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
665                 fWatchDebitCached = true;
666                 nDebit += nWatchDebitCached;
667             }
668         }
669
670         return nDebit;
671     }
672
673     int64_t GetCredit(const isminefilter& filter) const
674     {
675         // Must wait until coinbase is safely deep enough in the chain before valuing it
676         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
677             return 0;
678
679         int64_t credit = 0;
680         if (filter & MINE_SPENDABLE)
681         {
682             // GetBalance can assume transactions in mapWallet won't change
683             if (fCreditCached)
684                 credit += nCreditCached;
685             else
686             {
687                 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
688                 fCreditCached = true;
689                 credit += nCreditCached;
690             }
691         }
692         if (filter & MINE_WATCH_ONLY)
693         {
694             if (fWatchCreditCached)
695                 credit += nWatchCreditCached;
696             else
697             {
698                 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
699                 fWatchCreditCached = true;
700                 credit += nWatchCreditCached;
701             }
702         }
703         return credit;
704     }
705
706     int64_t GetImmatureCredit(bool fUseCache=true) const
707     {
708         if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
709         {
710             if (fUseCache && fImmatureCreditCached)
711                 return nImmatureCreditCached;
712             nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
713             fImmatureCreditCached = true;
714             return nImmatureCreditCached;
715         }
716
717         return 0;
718     }
719
720     int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const
721     {
722         if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
723         {
724             if (fUseCache && fImmatureWatchCreditCached)
725                 return nImmatureWatchCreditCached;
726             nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
727             fImmatureWatchCreditCached = true;
728             return nImmatureWatchCreditCached;
729         }
730
731         return 0;
732     }
733
734
735     int64_t GetAvailableCredit(bool fUseCache=true) const
736     {
737         // Must wait until coinbase is safely deep enough in the chain before valuing it
738         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
739             return 0;
740
741         if (fUseCache) {
742             if (fAvailableCreditCached)
743                 return nAvailableCreditCached;
744         }
745
746         int64_t nCredit = 0;
747         for (unsigned int i = 0; i < vout.size(); i++)
748         {
749             if (!IsSpent(i))
750             {
751                 const CTxOut &txout = vout[i];
752                 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
753                 if (!MoneyRange(nCredit))
754                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
755             }
756         }
757
758         nAvailableCreditCached = nCredit;
759         fAvailableCreditCached = true;
760
761         return nCredit;
762     }
763
764     int64_t GetAvailableWatchCredit(bool fUseCache=true) const
765     {
766         // Must wait until coinbase is safely deep enough in the chain before valuing it
767         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
768             return 0;
769
770         if (fUseCache) {
771             if (fAvailableWatchCreditCached)
772                 return nAvailableWatchCreditCached;
773         }
774
775         int64_t nCredit = 0;
776         for (unsigned int i = 0; i < vout.size(); i++)
777         {
778             if (!IsSpent(i))
779             {
780                 const CTxOut &txout = vout[i];
781                 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
782                 if (!MoneyRange(nCredit))
783                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
784             }
785         }
786
787         nAvailableWatchCreditCached = nCredit;
788         fAvailableWatchCreditCached = true;
789
790         return nCredit;
791     }
792
793     int64_t GetChange() const
794     {
795         if (fChangeCached)
796             return nChangeCached;
797         nChangeCached = pwallet->GetChange(*this);
798         fChangeCached = true;
799         return nChangeCached;
800     }
801
802     void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
803                     std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
804
805     void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
806                            int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
807
808     bool IsFromMe(const isminefilter& filter) const
809     {
810         return (GetDebit(filter) > 0);
811     }
812
813     bool IsTrusted() const
814     {
815         // Quick answer in most cases
816         if (!IsFinal())
817             return false;
818         if (GetDepthInMainChain() >= 1)
819             return true;
820         if (fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
821             return false;
822
823         // If no confirmations but it's from us, we can still
824         // consider it confirmed if all dependencies are confirmed
825         std::map<uint256, const CMerkleTx*> mapPrev;
826         std::vector<const CMerkleTx*> vWorkQueue;
827         vWorkQueue.reserve(vtxPrev.size()+1);
828         vWorkQueue.push_back(this);
829         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
830         {
831             const CMerkleTx* ptx = vWorkQueue[i];
832
833             if (!ptx->IsFinal())
834                 return false;
835             if (ptx->GetDepthInMainChain() >= 1)
836                 continue;
837             if (!pwallet->IsFromMe(*ptx))
838                 return false;
839
840             if (mapPrev.empty())
841             {
842                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
843                     mapPrev[tx.GetHash()] = &tx;
844             }
845
846             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
847             {
848                 if (!mapPrev.count(txin.prevout.hash))
849                     return false;
850                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
851             }
852         }
853
854         return true;
855     }
856
857     bool WriteToDisk();
858
859     int64_t GetTxTime() const;
860     int GetRequestCount() const;
861
862     void AddSupportingTransactions(CTxDB& txdb);
863
864     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
865     bool AcceptWalletTransaction();
866
867     void RelayWalletTransaction(CTxDB& txdb);
868     void RelayWalletTransaction();
869 };
870
871
872
873
874 class COutput
875 {
876 public:
877     const CWalletTx *tx;
878     int i;
879     int nDepth;
880     bool fSpendable;
881
882     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
883     {
884         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
885     }
886
887     std::string ToString() const
888     {
889         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());
890     }
891
892     void print() const
893     {
894         printf("%s\n", ToString().c_str());
895     }
896 };
897
898
899
900
901 /** Private key that includes an expiration date in case it never gets used. */
902 class CWalletKey
903 {
904 public:
905     CPrivKey vchPrivKey;
906     int64_t nTimeCreated;
907     int64_t nTimeExpires;
908     std::string strComment;
909     //// todo: add something to note what created it (user, getnewaddress, change)
910     ////   maybe should have a map<string, string> property map
911
912     CWalletKey(int64_t nExpires=0)
913     {
914         nTimeCreated = (nExpires ? GetTime() : 0);
915         nTimeExpires = nExpires;
916     }
917
918     IMPLEMENT_SERIALIZE
919     (
920         if (!(nType & SER_GETHASH))
921             READWRITE(nVersion);
922         READWRITE(vchPrivKey);
923         READWRITE(nTimeCreated);
924         READWRITE(nTimeExpires);
925         READWRITE(strComment);
926     )
927 };
928
929
930
931
932
933
934 /** Account information.
935  * Stored in wallet with key "acc"+string account name.
936  */
937 class CAccount
938 {
939 public:
940     CPubKey vchPubKey;
941
942     CAccount()
943     {
944         SetNull();
945     }
946
947     void SetNull()
948     {
949         vchPubKey = CPubKey();
950     }
951
952     IMPLEMENT_SERIALIZE
953     (
954         if (!(nType & SER_GETHASH))
955             READWRITE(nVersion);
956         READWRITE(vchPubKey);
957     )
958 };
959
960
961
962 /** Internal transfers.
963  * Database key is acentry<account><counter>.
964  */
965 class CAccountingEntry
966 {
967 public:
968     std::string strAccount;
969     int64_t nCreditDebit;
970     int64_t nTime;
971     std::string strOtherAccount;
972     std::string strComment;
973     mapValue_t mapValue;
974     int64_t nOrderPos;  // position in ordered transaction list
975     uint64_t nEntryNo;
976
977     CAccountingEntry()
978     {
979         SetNull();
980     }
981
982     void SetNull()
983     {
984         nCreditDebit = 0;
985         nTime = 0;
986         strAccount.clear();
987         strOtherAccount.clear();
988         strComment.clear();
989         nOrderPos = -1;
990     }
991
992     IMPLEMENT_SERIALIZE
993     (
994         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
995         if (!(nType & SER_GETHASH))
996             READWRITE(nVersion);
997         // Note: strAccount is serialized as part of the key, not here.
998         READWRITE(nCreditDebit);
999         READWRITE(nTime);
1000         READWRITE(strOtherAccount);
1001
1002         if (!fRead)
1003         {
1004             WriteOrderPos(nOrderPos, me.mapValue);
1005
1006             if (!(mapValue.empty() && _ssExtra.empty()))
1007             {
1008                 CDataStream ss(nType, nVersion);
1009                 ss.insert(ss.begin(), '\0');
1010                 ss << mapValue;
1011                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1012                 me.strComment.append(ss.str());
1013             }
1014         }
1015
1016         READWRITE(strComment);
1017
1018         size_t nSepPos = strComment.find("\0", 0, 1);
1019         if (fRead)
1020         {
1021             me.mapValue.clear();
1022             if (std::string::npos != nSepPos)
1023             {
1024                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1025                 ss >> me.mapValue;
1026                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
1027             }
1028             ReadOrderPos(me.nOrderPos, me.mapValue);
1029         }
1030         if (std::string::npos != nSepPos)
1031             me.strComment.erase(nSepPos);
1032
1033         me.mapValue.erase("n");
1034     )
1035
1036 private:
1037     std::vector<char> _ssExtra;
1038 };
1039
1040 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
1041
1042 #endif