Add wallet privkey encryption.
[novacoin.git] / src / wallet.h
1 // Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_WALLET_H
5 #define BITCOIN_WALLET_H
6
7 #include "bignum.h"
8 #include "key.h"
9 #include "script.h"
10
11 class CWalletTx;
12 class CReserveKey;
13 class CWalletDB;
14
15 class CWallet : public CCryptoKeyStore
16 {
17 private:
18     bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
19     bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
20
21
22 public:
23     bool fFileBacked;
24     std::string strWalletFile;
25
26     std::set<int64> setKeyPool;
27     CCriticalSection cs_setKeyPool;
28
29     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
30     MasterKeyMap mapMasterKeys;
31     unsigned int nMasterKeyMaxID;
32
33     CWallet()
34     {
35         fFileBacked = false;
36         nMasterKeyMaxID = 0;
37     }
38     CWallet(std::string strWalletFileIn)
39     {
40         strWalletFile = strWalletFileIn;
41         fFileBacked = true;
42         nMasterKeyMaxID = 0;
43     }
44
45     mutable CCriticalSection cs_mapWallet;
46     std::map<uint256, CWalletTx> mapWallet;
47     std::vector<uint256> vWalletUpdated;
48
49     std::map<uint256, int> mapRequestCount;
50     mutable CCriticalSection cs_mapRequestCount;
51
52     std::map<std::string, std::string> mapAddressBook;
53     mutable CCriticalSection cs_mapAddressBook;
54
55     std::vector<unsigned char> vchDefaultKey;
56
57     // keystore implementation
58     bool AddKey(const CKey& key);
59     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
60     bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
61     bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
62
63     bool Unlock(const std::string& strWalletPassphrase);
64     bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
65     bool EncryptWallet(const std::string& strWalletPassphrase);
66
67     bool AddToWallet(const CWalletTx& wtxIn);
68     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
69     bool EraseFromWallet(uint256 hash);
70     void WalletUpdateSpent(const CTransaction& prevout);
71     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
72     void ReacceptWalletTransactions();
73     void ResendWalletTransactions();
74     int64 GetBalance() const;
75     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
76     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
77     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
78     bool BroadcastTransaction(CWalletTx& wtxNew);
79     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
80     std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
81
82     bool TopUpKeyPool();
83     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
84     void KeepKey(int64 nIndex);
85     void ReturnKey(int64 nIndex);
86     std::vector<unsigned char> GetOrReuseKeyFromPool();
87     int64 GetOldestKeyPoolTime();
88
89     bool IsMine(const CTxIn& txin) const;
90     int64 GetDebit(const CTxIn& txin) const;
91     bool IsMine(const CTxOut& txout) const
92     {
93         return ::IsMine(*this, txout.scriptPubKey);
94     }
95     int64 GetCredit(const CTxOut& txout) const
96     {
97         if (!MoneyRange(txout.nValue))
98             throw std::runtime_error("CWallet::GetCredit() : value out of range");
99         return (IsMine(txout) ? txout.nValue : 0);
100     }
101     bool IsChange(const CTxOut& txout) const
102     {
103         std::vector<unsigned char> vchPubKey;
104         if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
105             CRITICAL_BLOCK(cs_mapAddressBook)
106                 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
107                     return true;
108         return false;
109     }
110     int64 GetChange(const CTxOut& txout) const
111     {
112         if (!MoneyRange(txout.nValue))
113             throw std::runtime_error("CWallet::GetChange() : value out of range");
114         return (IsChange(txout) ? txout.nValue : 0);
115     }
116     bool IsMine(const CTransaction& tx) const
117     {
118         BOOST_FOREACH(const CTxOut& txout, tx.vout)
119             if (IsMine(txout))
120                 return true;
121         return false;
122     }
123     bool IsFromMe(const CTransaction& tx) const
124     {
125         return (GetDebit(tx) > 0);
126     }
127     int64 GetDebit(const CTransaction& tx) const
128     {
129         int64 nDebit = 0;
130         BOOST_FOREACH(const CTxIn& txin, tx.vin)
131         {
132             nDebit += GetDebit(txin);
133             if (!MoneyRange(nDebit))
134                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
135         }
136         return nDebit;
137     }
138     int64 GetCredit(const CTransaction& tx) const
139     {
140         int64 nCredit = 0;
141         BOOST_FOREACH(const CTxOut& txout, tx.vout)
142         {
143             nCredit += GetCredit(txout);
144             if (!MoneyRange(nCredit))
145                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
146         }
147         return nCredit;
148     }
149     int64 GetChange(const CTransaction& tx) const
150     {
151         int64 nChange = 0;
152         BOOST_FOREACH(const CTxOut& txout, tx.vout)
153         {
154             nChange += GetChange(txout);
155             if (!MoneyRange(nChange))
156                 throw std::runtime_error("CWallet::GetChange() : value out of range");
157         }
158         return nChange;
159     }
160     void SetBestChain(const CBlockLocator& loc)
161     {
162         CWalletDB walletdb(strWalletFile);
163         walletdb.WriteBestBlock(loc);
164     }
165
166     bool LoadWallet(bool& fFirstRunRet);
167 //    bool BackupWallet(const std::string& strDest);
168
169     // requires cs_mapAddressBook lock
170     bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
171
172     // requires cs_mapAddressBook lock
173     bool DelAddressBookName(const std::string& strAddress);
174
175     void UpdatedTransaction(const uint256 &hashTx)
176     {
177         CRITICAL_BLOCK(cs_mapWallet)
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_mapRequestCount)
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 (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 (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<std::string /* address */, int64> >& listReceived,
464                     std::list<std::pair<std::string /* address */, 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 (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                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
503                     mapPrev[tx.GetHash()] = &tx;
504
505             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
506             {
507                 if (!mapPrev.count(txin.prevout.hash))
508                     return false;
509                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
510             }
511         }
512         return true;
513     }
514
515     bool WriteToDisk();
516
517     int64 GetTxTime() const;
518     int GetRequestCount() const;
519
520     void AddSupportingTransactions(CTxDB& txdb);
521
522     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
523     bool AcceptWalletTransaction();
524
525     void RelayWalletTransaction(CTxDB& txdb);
526     void RelayWalletTransaction();
527 };
528
529
530 //
531 // Private key that includes an expiration date in case it never gets used.
532 //
533 class CWalletKey
534 {
535 public:
536     CPrivKey vchPrivKey;
537     int64 nTimeCreated;
538     int64 nTimeExpires;
539     std::string strComment;
540     //// todo: add something to note what created it (user, getnewaddress, change)
541     ////   maybe should have a map<string, string> property map
542
543     CWalletKey(int64 nExpires=0)
544     {
545         nTimeCreated = (nExpires ? GetTime() : 0);
546         nTimeExpires = nExpires;
547     }
548
549     IMPLEMENT_SERIALIZE
550     (
551         if (!(nType & SER_GETHASH))
552             READWRITE(nVersion);
553         READWRITE(vchPrivKey);
554         READWRITE(nTimeCreated);
555         READWRITE(nTimeExpires);
556         READWRITE(strComment);
557     )
558 };
559
560
561
562
563
564
565 //
566 // Account information.
567 // Stored in wallet with key "acc"+string account name
568 //
569 class CAccount
570 {
571 public:
572     std::vector<unsigned char> vchPubKey;
573
574     CAccount()
575     {
576         SetNull();
577     }
578
579     void SetNull()
580     {
581         vchPubKey.clear();
582     }
583
584     IMPLEMENT_SERIALIZE
585     (
586         if (!(nType & SER_GETHASH))
587             READWRITE(nVersion);
588         READWRITE(vchPubKey);
589     )
590 };
591
592
593
594 //
595 // Internal transfers.
596 // Database key is acentry<account><counter>
597 //
598 class CAccountingEntry
599 {
600 public:
601     std::string strAccount;
602     int64 nCreditDebit;
603     int64 nTime;
604     std::string strOtherAccount;
605     std::string strComment;
606
607     CAccountingEntry()
608     {
609         SetNull();
610     }
611
612     void SetNull()
613     {
614         nCreditDebit = 0;
615         nTime = 0;
616         strAccount.clear();
617         strOtherAccount.clear();
618         strComment.clear();
619     }
620
621     IMPLEMENT_SERIALIZE
622     (
623         if (!(nType & SER_GETHASH))
624             READWRITE(nVersion);
625         // Note: strAccount is serialized as part of the key, not here.
626         READWRITE(nCreditDebit);
627         READWRITE(nTime);
628         READWRITE(strOtherAccount);
629         READWRITE(strComment);
630     )
631 };
632
633 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
634
635 #endif