Fix loop index var types, fixing many minor sign comparison warnings
[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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
7
8 #include "bignum.h"
9 #include "key.h"
10 #include "script.h"
11
12 class CWalletTx;
13 class CReserveKey;
14 class CWalletDB;
15
16 class CWallet : public CCryptoKeyStore
17 {
18 private:
19     bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
20     bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
21
22     CWalletDB *pwalletdbEncryption;
23
24 public:
25     mutable CCriticalSection cs_wallet;
26
27     bool fFileBacked;
28     std::string strWalletFile;
29
30     std::set<int64> setKeyPool;
31
32     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
33     MasterKeyMap mapMasterKeys;
34     unsigned int nMasterKeyMaxID;
35
36     CWallet()
37     {
38         fFileBacked = false;
39         nMasterKeyMaxID = 0;
40         pwalletdbEncryption = NULL;
41     }
42     CWallet(std::string strWalletFileIn)
43     {
44         strWalletFile = strWalletFileIn;
45         fFileBacked = true;
46         nMasterKeyMaxID = 0;
47         pwalletdbEncryption = NULL;
48     }
49
50     std::map<uint256, CWalletTx> mapWallet;
51     std::vector<uint256> vWalletUpdated;
52
53     std::map<uint256, int> mapRequestCount;
54
55     std::map<CBitcoinAddress, std::string> mapAddressBook;
56
57     std::vector<unsigned char> vchDefaultKey;
58
59     // keystore implementation
60     bool AddKey(const CKey& key);
61     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
62     bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
63     bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
64
65     bool Unlock(const std::string& strWalletPassphrase);
66     bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
67     bool EncryptWallet(const std::string& strWalletPassphrase);
68
69     bool AddToWallet(const CWalletTx& wtxIn);
70     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
71     bool EraseFromWallet(uint256 hash);
72     void WalletUpdateSpent(const CTransaction& prevout);
73     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
74     void ReacceptWalletTransactions();
75     void ResendWalletTransactions();
76     int64 GetBalance() const;
77     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
78     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
79     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
80     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
81     std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
82
83     bool NewKeyPool();
84     bool TopUpKeyPool();
85     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
86     void KeepKey(int64 nIndex);
87     void ReturnKey(int64 nIndex);
88     bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
89     int64 GetOldestKeyPoolTime();
90
91     bool IsMine(const CTxIn& txin) const;
92     int64 GetDebit(const CTxIn& txin) const;
93     bool IsMine(const CTxOut& txout) const
94     {
95         return ::IsMine(*this, txout.scriptPubKey);
96     }
97     int64 GetCredit(const CTxOut& txout) const
98     {
99         if (!MoneyRange(txout.nValue))
100             throw std::runtime_error("CWallet::GetCredit() : value out of range");
101         return (IsMine(txout) ? txout.nValue : 0);
102     }
103     bool IsChange(const CTxOut& txout) const
104     {
105         CBitcoinAddress address;
106         if (ExtractAddress(txout.scriptPubKey, this, address))
107             CRITICAL_BLOCK(cs_wallet)
108                 if (!mapAddressBook.count(address))
109                     return true;
110         return false;
111     }
112     int64 GetChange(const CTxOut& txout) const
113     {
114         if (!MoneyRange(txout.nValue))
115             throw std::runtime_error("CWallet::GetChange() : value out of range");
116         return (IsChange(txout) ? txout.nValue : 0);
117     }
118     bool IsMine(const CTransaction& tx) const
119     {
120         BOOST_FOREACH(const CTxOut& txout, tx.vout)
121             if (IsMine(txout))
122                 return true;
123         return false;
124     }
125     bool IsFromMe(const CTransaction& tx) const
126     {
127         return (GetDebit(tx) > 0);
128     }
129     int64 GetDebit(const CTransaction& tx) const
130     {
131         int64 nDebit = 0;
132         BOOST_FOREACH(const CTxIn& txin, tx.vin)
133         {
134             nDebit += GetDebit(txin);
135             if (!MoneyRange(nDebit))
136                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
137         }
138         return nDebit;
139     }
140     int64 GetCredit(const CTransaction& tx) const
141     {
142         int64 nCredit = 0;
143         BOOST_FOREACH(const CTxOut& txout, tx.vout)
144         {
145             nCredit += GetCredit(txout);
146             if (!MoneyRange(nCredit))
147                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
148         }
149         return nCredit;
150     }
151     int64 GetChange(const CTransaction& tx) const
152     {
153         int64 nChange = 0;
154         BOOST_FOREACH(const CTxOut& txout, tx.vout)
155         {
156             nChange += GetChange(txout);
157             if (!MoneyRange(nChange))
158                 throw std::runtime_error("CWallet::GetChange() : value out of range");
159         }
160         return nChange;
161     }
162     void SetBestChain(const CBlockLocator& loc)
163     {
164         CWalletDB walletdb(strWalletFile);
165         walletdb.WriteBestBlock(loc);
166     }
167
168     int LoadWallet(bool& fFirstRunRet);
169 //    bool BackupWallet(const std::string& strDest);
170
171     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
172
173     bool DelAddressBookName(const CBitcoinAddress& address);
174
175     void UpdatedTransaction(const uint256 &hashTx)
176     {
177         CRITICAL_BLOCK(cs_wallet)
178             vWalletUpdated.push_back(hashTx);
179     }
180
181     void PrintWallet(const CBlock& block);
182
183     void Inventory(const uint256 &hash)
184     {
185         CRITICAL_BLOCK(cs_wallet)
186         {
187             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
188             if (mi != mapRequestCount.end())
189                 (*mi).second++;
190         }
191     }
192
193     int GetKeyPoolSize()
194     {
195         return setKeyPool.size();
196     }
197
198     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
199
200     bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
201 };
202
203
204 class CReserveKey
205 {
206 protected:
207     CWallet* pwallet;
208     int64 nIndex;
209     std::vector<unsigned char> vchPubKey;
210 public:
211     CReserveKey(CWallet* pwalletIn)
212     {
213         nIndex = -1;
214         pwallet = pwalletIn;
215     }
216
217     ~CReserveKey()
218     {
219         if (!fShutdown)
220             ReturnKey();
221     }
222
223     void ReturnKey();
224     std::vector<unsigned char> GetReservedKey();
225     void KeepKey();
226 };
227
228
229 //
230 // A transaction with a bunch of additional info that only the owner cares
231 // about.  It includes any unrecorded transactions needed to link it back
232 // to the block chain.
233 //
234 class CWalletTx : public CMerkleTx
235 {
236 public:
237     const CWallet* pwallet;
238
239     std::vector<CMerkleTx> vtxPrev;
240     std::map<std::string, std::string> mapValue;
241     std::vector<std::pair<std::string, std::string> > vOrderForm;
242     unsigned int fTimeReceivedIsTxTime;
243     unsigned int nTimeReceived;  // time received by this node
244     char fFromMe;
245     std::string strFromAccount;
246     std::vector<char> vfSpent;
247
248     // memory only
249     mutable char fDebitCached;
250     mutable char fCreditCached;
251     mutable char fAvailableCreditCached;
252     mutable char fChangeCached;
253     mutable int64 nDebitCached;
254     mutable int64 nCreditCached;
255     mutable int64 nAvailableCreditCached;
256     mutable int64 nChangeCached;
257
258     // memory only UI hints
259     mutable unsigned int nTimeDisplayed;
260     mutable int nLinesDisplayed;
261     mutable char fConfirmedDisplayed;
262
263     CWalletTx()
264     {
265         Init(NULL);
266     }
267
268     CWalletTx(const CWallet* pwalletIn)
269     {
270         Init(pwalletIn);
271     }
272
273     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
274     {
275         Init(pwalletIn);
276     }
277
278     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
279     {
280         Init(pwalletIn);
281     }
282
283     void Init(const CWallet* pwalletIn)
284     {
285         pwallet = pwalletIn;
286         vtxPrev.clear();
287         mapValue.clear();
288         vOrderForm.clear();
289         fTimeReceivedIsTxTime = false;
290         nTimeReceived = 0;
291         fFromMe = false;
292         strFromAccount.clear();
293         vfSpent.clear();
294         fDebitCached = false;
295         fCreditCached = false;
296         fAvailableCreditCached = false;
297         fChangeCached = false;
298         nDebitCached = 0;
299         nCreditCached = 0;
300         nAvailableCreditCached = 0;
301         nChangeCached = 0;
302         nTimeDisplayed = 0;
303         nLinesDisplayed = 0;
304         fConfirmedDisplayed = false;
305     }
306
307     IMPLEMENT_SERIALIZE
308     (
309         CWalletTx* pthis = const_cast<CWalletTx*>(this);
310         if (fRead)
311             pthis->Init(NULL);
312         char fSpent = false;
313
314         if (!fRead)
315         {
316             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
317
318             std::string str;
319             BOOST_FOREACH(char f, vfSpent)
320             {
321                 str += (f ? '1' : '0');
322                 if (f)
323                     fSpent = true;
324             }
325             pthis->mapValue["spent"] = str;
326         }
327
328         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
329         READWRITE(vtxPrev);
330         READWRITE(mapValue);
331         READWRITE(vOrderForm);
332         READWRITE(fTimeReceivedIsTxTime);
333         READWRITE(nTimeReceived);
334         READWRITE(fFromMe);
335         READWRITE(fSpent);
336
337         if (fRead)
338         {
339             pthis->strFromAccount = pthis->mapValue["fromaccount"];
340
341             if (mapValue.count("spent"))
342                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
343                     pthis->vfSpent.push_back(c != '0');
344             else
345                 pthis->vfSpent.assign(vout.size(), fSpent);
346         }
347
348         pthis->mapValue.erase("fromaccount");
349         pthis->mapValue.erase("version");
350         pthis->mapValue.erase("spent");
351     )
352
353     // marks certain txout's as spent
354     // returns true if any update took place
355     bool UpdateSpent(const std::vector<char>& vfNewSpent)
356     {
357         bool fReturn = false;
358         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
359         {
360             if (i == vfSpent.size())
361                 break;
362
363             if (vfNewSpent[i] && !vfSpent[i])
364             {
365                 vfSpent[i] = true;
366                 fReturn = true;
367                 fAvailableCreditCached = false;
368             }
369         }
370         return fReturn;
371     }
372
373     void MarkDirty()
374     {
375         fCreditCached = false;
376         fAvailableCreditCached = false;
377         fDebitCached = false;
378         fChangeCached = false;
379     }
380
381     void MarkSpent(unsigned int nOut)
382     {
383         if (nOut >= vout.size())
384             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
385         vfSpent.resize(vout.size());
386         if (!vfSpent[nOut])
387         {
388             vfSpent[nOut] = true;
389             fAvailableCreditCached = false;
390         }
391     }
392
393     bool IsSpent(unsigned int nOut) const
394     {
395         if (nOut >= vout.size())
396             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
397         if (nOut >= vfSpent.size())
398             return false;
399         return (!!vfSpent[nOut]);
400     }
401
402     int64 GetDebit() const
403     {
404         if (vin.empty())
405             return 0;
406         if (fDebitCached)
407             return nDebitCached;
408         nDebitCached = pwallet->GetDebit(*this);
409         fDebitCached = true;
410         return nDebitCached;
411     }
412
413     int64 GetCredit(bool fUseCache=true) const
414     {
415         // Must wait until coinbase is safely deep enough in the chain before valuing it
416         if (IsCoinBase() && GetBlocksToMaturity() > 0)
417             return 0;
418
419         // GetBalance can assume transactions in mapWallet won't change
420         if (fUseCache && fCreditCached)
421             return nCreditCached;
422         nCreditCached = pwallet->GetCredit(*this);
423         fCreditCached = true;
424         return nCreditCached;
425     }
426
427     int64 GetAvailableCredit(bool fUseCache=true) const
428     {
429         // Must wait until coinbase is safely deep enough in the chain before valuing it
430         if (IsCoinBase() && GetBlocksToMaturity() > 0)
431             return 0;
432
433         if (fUseCache && fAvailableCreditCached)
434             return nAvailableCreditCached;
435
436         int64 nCredit = 0;
437         for (unsigned int i = 0; i < vout.size(); i++)
438         {
439             if (!IsSpent(i))
440             {
441                 const CTxOut &txout = vout[i];
442                 nCredit += pwallet->GetCredit(txout);
443                 if (!MoneyRange(nCredit))
444                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
445             }
446         }
447
448         nAvailableCreditCached = nCredit;
449         fAvailableCreditCached = true;
450         return nCredit;
451     }
452
453
454     int64 GetChange() const
455     {
456         if (fChangeCached)
457             return nChangeCached;
458         nChangeCached = pwallet->GetChange(*this);
459         fChangeCached = true;
460         return nChangeCached;
461     }
462
463     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
464                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
465
466     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
467                            int64& nSent, int64& nFee) const;
468
469     bool IsFromMe() const
470     {
471         return (GetDebit() > 0);
472     }
473
474     bool IsConfirmed() const
475     {
476         // Quick answer in most cases
477         if (!IsFinal())
478             return false;
479         if (GetDepthInMainChain() >= 1)
480             return true;
481         if (!IsFromMe()) // using wtx's cached debit
482             return false;
483
484         // If no confirmations but it's from us, we can still
485         // consider it confirmed if all dependencies are confirmed
486         std::map<uint256, const CMerkleTx*> mapPrev;
487         std::vector<const CMerkleTx*> vWorkQueue;
488         vWorkQueue.reserve(vtxPrev.size()+1);
489         vWorkQueue.push_back(this);
490         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
491         {
492             const CMerkleTx* ptx = vWorkQueue[i];
493
494             if (!ptx->IsFinal())
495                 return false;
496             if (ptx->GetDepthInMainChain() >= 1)
497                 continue;
498             if (!pwallet->IsFromMe(*ptx))
499                 return false;
500
501             if (mapPrev.empty())
502             {
503                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
504                     mapPrev[tx.GetHash()] = &tx;
505             }
506
507             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
508             {
509                 if (!mapPrev.count(txin.prevout.hash))
510                     return false;
511                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
512             }
513         }
514         return true;
515     }
516
517     bool WriteToDisk();
518
519     int64 GetTxTime() const;
520     int GetRequestCount() const;
521
522     void AddSupportingTransactions(CTxDB& txdb);
523
524     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
525     bool AcceptWalletTransaction();
526
527     void RelayWalletTransaction(CTxDB& txdb);
528     void RelayWalletTransaction();
529 };
530
531
532 //
533 // Private key that includes an expiration date in case it never gets used.
534 //
535 class CWalletKey
536 {
537 public:
538     CPrivKey vchPrivKey;
539     int64 nTimeCreated;
540     int64 nTimeExpires;
541     std::string strComment;
542     //// todo: add something to note what created it (user, getnewaddress, change)
543     ////   maybe should have a map<string, string> property map
544
545     CWalletKey(int64 nExpires=0)
546     {
547         nTimeCreated = (nExpires ? GetTime() : 0);
548         nTimeExpires = nExpires;
549     }
550
551     IMPLEMENT_SERIALIZE
552     (
553         if (!(nType & SER_GETHASH))
554             READWRITE(nVersion);
555         READWRITE(vchPrivKey);
556         READWRITE(nTimeCreated);
557         READWRITE(nTimeExpires);
558         READWRITE(strComment);
559     )
560 };
561
562
563
564
565
566
567 //
568 // Account information.
569 // Stored in wallet with key "acc"+string account name
570 //
571 class CAccount
572 {
573 public:
574     std::vector<unsigned char> vchPubKey;
575
576     CAccount()
577     {
578         SetNull();
579     }
580
581     void SetNull()
582     {
583         vchPubKey.clear();
584     }
585
586     IMPLEMENT_SERIALIZE
587     (
588         if (!(nType & SER_GETHASH))
589             READWRITE(nVersion);
590         READWRITE(vchPubKey);
591     )
592 };
593
594
595
596 //
597 // Internal transfers.
598 // Database key is acentry<account><counter>
599 //
600 class CAccountingEntry
601 {
602 public:
603     std::string strAccount;
604     int64 nCreditDebit;
605     int64 nTime;
606     std::string strOtherAccount;
607     std::string strComment;
608
609     CAccountingEntry()
610     {
611         SetNull();
612     }
613
614     void SetNull()
615     {
616         nCreditDebit = 0;
617         nTime = 0;
618         strAccount.clear();
619         strOtherAccount.clear();
620         strComment.clear();
621     }
622
623     IMPLEMENT_SERIALIZE
624     (
625         if (!(nType & SER_GETHASH))
626             READWRITE(nVersion);
627         // Note: strAccount is serialized as part of the key, not here.
628         READWRITE(nCreditDebit);
629         READWRITE(nTime);
630         READWRITE(strOtherAccount);
631         READWRITE(strComment);
632     )
633 };
634
635 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
636
637 #endif