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