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