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