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