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