Merge branch '0.4.x' into 0.5.0.x
[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 "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     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
90     std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
91
92     bool NewKeyPool();
93     bool TopUpKeyPool();
94     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
95     void KeepKey(int64 nIndex);
96     void ReturnKey(int64 nIndex);
97     bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
98     int64 GetOldestKeyPoolTime();
99
100     bool IsMine(const CTxIn& txin) const;
101     int64 GetDebit(const CTxIn& txin) const;
102     bool IsMine(const CTxOut& txout) const
103     {
104         return ::IsMine(*this, txout.scriptPubKey);
105     }
106     int64 GetCredit(const CTxOut& txout) const
107     {
108         if (!MoneyRange(txout.nValue))
109             throw std::runtime_error("CWallet::GetCredit() : value out of range");
110         return (IsMine(txout) ? txout.nValue : 0);
111     }
112     bool IsChange(const CTxOut& txout) const
113     {
114         CBitcoinAddress address;
115         if (ExtractAddress(txout.scriptPubKey, this, address))
116             CRITICAL_BLOCK(cs_wallet)
117                 if (!mapAddressBook.count(address))
118                     return true;
119         return false;
120     }
121     int64 GetChange(const CTxOut& txout) const
122     {
123         if (!MoneyRange(txout.nValue))
124             throw std::runtime_error("CWallet::GetChange() : value out of range");
125         return (IsChange(txout) ? txout.nValue : 0);
126     }
127     bool IsMine(const CTransaction& tx) const
128     {
129         BOOST_FOREACH(const CTxOut& txout, tx.vout)
130             if (IsMine(txout))
131                 return true;
132         return false;
133     }
134     bool IsFromMe(const CTransaction& tx) const
135     {
136         return (GetDebit(tx) > 0);
137     }
138     int64 GetDebit(const CTransaction& tx) const
139     {
140         int64 nDebit = 0;
141         BOOST_FOREACH(const CTxIn& txin, tx.vin)
142         {
143             nDebit += GetDebit(txin);
144             if (!MoneyRange(nDebit))
145                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
146         }
147         return nDebit;
148     }
149     int64 GetCredit(const CTransaction& tx) const
150     {
151         int64 nCredit = 0;
152         BOOST_FOREACH(const CTxOut& txout, tx.vout)
153         {
154             nCredit += GetCredit(txout);
155             if (!MoneyRange(nCredit))
156                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
157         }
158         return nCredit;
159     }
160     int64 GetChange(const CTransaction& tx) const
161     {
162         int64 nChange = 0;
163         BOOST_FOREACH(const CTxOut& txout, tx.vout)
164         {
165             nChange += GetChange(txout);
166             if (!MoneyRange(nChange))
167                 throw std::runtime_error("CWallet::GetChange() : value out of range");
168         }
169         return nChange;
170     }
171     void SetBestChain(const CBlockLocator& loc)
172     {
173         CWalletDB walletdb(strWalletFile);
174         walletdb.WriteBestBlock(loc);
175     }
176
177     int LoadWallet(bool& fFirstRunRet);
178 //    bool BackupWallet(const std::string& strDest);
179
180     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
181
182     bool DelAddressBookName(const CBitcoinAddress& address);
183
184     void UpdatedTransaction(const uint256 &hashTx)
185     {
186         CRITICAL_BLOCK(cs_wallet)
187             vWalletUpdated.push_back(hashTx);
188     }
189
190     void PrintWallet(const CBlock& block);
191
192     void Inventory(const uint256 &hash)
193     {
194         CRITICAL_BLOCK(cs_wallet)
195         {
196             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
197             if (mi != mapRequestCount.end())
198                 (*mi).second++;
199         }
200     }
201
202     int GetKeyPoolSize()
203     {
204         return setKeyPool.size();
205     }
206
207     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
208
209     bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
210 };
211
212
213 class CReserveKey
214 {
215 protected:
216     CWallet* pwallet;
217     int64 nIndex;
218     std::vector<unsigned char> vchPubKey;
219 public:
220     CReserveKey(CWallet* pwalletIn)
221     {
222         nIndex = -1;
223         pwallet = pwalletIn;
224     }
225
226     ~CReserveKey()
227     {
228         if (!fShutdown)
229             ReturnKey();
230     }
231
232     void ReturnKey();
233     std::vector<unsigned char> GetReservedKey();
234     void KeepKey();
235 };
236
237
238 //
239 // A transaction with a bunch of additional info that only the owner cares
240 // about.  It includes any unrecorded transactions needed to link it back
241 // to the block chain.
242 //
243 class CWalletTx : public CMerkleTx
244 {
245 public:
246     const CWallet* pwallet;
247
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 MarkSpent(unsigned int nOut)
392     {
393         if (nOut >= vout.size())
394             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
395         vfSpent.resize(vout.size());
396         if (!vfSpent[nOut])
397         {
398             vfSpent[nOut] = true;
399             fAvailableCreditCached = false;
400         }
401     }
402
403     bool IsSpent(unsigned int nOut) const
404     {
405         if (nOut >= vout.size())
406             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
407         if (nOut >= vfSpent.size())
408             return false;
409         return (!!vfSpent[nOut]);
410     }
411
412     int64 GetDebit() const
413     {
414         if (vin.empty())
415             return 0;
416         if (fDebitCached)
417             return nDebitCached;
418         nDebitCached = pwallet->GetDebit(*this);
419         fDebitCached = true;
420         return nDebitCached;
421     }
422
423     int64 GetCredit(bool fUseCache=true) const
424     {
425         // Must wait until coinbase is safely deep enough in the chain before valuing it
426         if (IsCoinBase() && GetBlocksToMaturity() > 0)
427             return 0;
428
429         // GetBalance can assume transactions in mapWallet won't change
430         if (fUseCache && fCreditCached)
431             return nCreditCached;
432         nCreditCached = pwallet->GetCredit(*this);
433         fCreditCached = true;
434         return nCreditCached;
435     }
436
437     int64 GetAvailableCredit(bool fUseCache=true) const
438     {
439         // Must wait until coinbase is safely deep enough in the chain before valuing it
440         if (IsCoinBase() && GetBlocksToMaturity() > 0)
441             return 0;
442
443         if (fUseCache && fAvailableCreditCached)
444             return nAvailableCreditCached;
445
446         int64 nCredit = 0;
447         for (int i = 0; i < vout.size(); i++)
448         {
449             if (!IsSpent(i))
450             {
451                 const CTxOut &txout = vout[i];
452                 nCredit += pwallet->GetCredit(txout);
453                 if (!MoneyRange(nCredit))
454                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
455             }
456         }
457
458         nAvailableCreditCached = nCredit;
459         fAvailableCreditCached = true;
460         return nCredit;
461     }
462
463
464     int64 GetChange() const
465     {
466         if (fChangeCached)
467             return nChangeCached;
468         nChangeCached = pwallet->GetChange(*this);
469         fChangeCached = true;
470         return nChangeCached;
471     }
472
473     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
474                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
475
476     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
477                            int64& nSent, int64& nFee) const;
478
479     bool IsFromMe() const
480     {
481         return (GetDebit() > 0);
482     }
483
484     bool IsConfirmed() const
485     {
486         // Quick answer in most cases
487         if (!IsFinal())
488             return false;
489         if (GetDepthInMainChain() >= 1)
490             return true;
491         if (!IsFromMe()) // using wtx's cached debit
492             return false;
493
494         // If no confirmations but it's from us, we can still
495         // consider it confirmed if all dependencies are confirmed
496         std::map<uint256, const CMerkleTx*> mapPrev;
497         std::vector<const CMerkleTx*> vWorkQueue;
498         vWorkQueue.reserve(vtxPrev.size()+1);
499         vWorkQueue.push_back(this);
500         for (int i = 0; i < vWorkQueue.size(); i++)
501         {
502             const CMerkleTx* ptx = vWorkQueue[i];
503
504             if (!ptx->IsFinal())
505                 return false;
506             if (ptx->GetDepthInMainChain() >= 1)
507                 continue;
508             if (!pwallet->IsFromMe(*ptx))
509                 return false;
510
511             if (mapPrev.empty())
512             {
513                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
514                     mapPrev[tx.GetHash()] = &tx;
515             }
516
517             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
518             {
519                 if (!mapPrev.count(txin.prevout.hash))
520                     return false;
521                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
522             }
523         }
524         return true;
525     }
526
527     bool WriteToDisk();
528
529     int64 GetTxTime() const;
530     int GetRequestCount() const;
531
532     void AddSupportingTransactions(CTxDB& txdb);
533
534     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
535     bool AcceptWalletTransaction();
536
537     void RelayWalletTransaction(CTxDB& txdb);
538     void RelayWalletTransaction();
539 };
540
541
542 //
543 // Private key that includes an expiration date in case it never gets used.
544 //
545 class CWalletKey
546 {
547 public:
548     CPrivKey vchPrivKey;
549     int64 nTimeCreated;
550     int64 nTimeExpires;
551     std::string strComment;
552     //// todo: add something to note what created it (user, getnewaddress, change)
553     ////   maybe should have a map<string, string> property map
554
555     CWalletKey(int64 nExpires=0)
556     {
557         nTimeCreated = (nExpires ? GetTime() : 0);
558         nTimeExpires = nExpires;
559     }
560
561     IMPLEMENT_SERIALIZE
562     (
563         if (!(nType & SER_GETHASH))
564             READWRITE(nVersion);
565         READWRITE(vchPrivKey);
566         READWRITE(nTimeCreated);
567         READWRITE(nTimeExpires);
568         READWRITE(strComment);
569     )
570 };
571
572
573
574
575
576
577 //
578 // Account information.
579 // Stored in wallet with key "acc"+string account name
580 //
581 class CAccount
582 {
583 public:
584     std::vector<unsigned char> vchPubKey;
585
586     CAccount()
587     {
588         SetNull();
589     }
590
591     void SetNull()
592     {
593         vchPubKey.clear();
594     }
595
596     IMPLEMENT_SERIALIZE
597     (
598         if (!(nType & SER_GETHASH))
599             READWRITE(nVersion);
600         READWRITE(vchPubKey);
601     )
602 };
603
604
605
606 //
607 // Internal transfers.
608 // Database key is acentry<account><counter>
609 //
610 class CAccountingEntry
611 {
612 public:
613     std::string strAccount;
614     int64 nCreditDebit;
615     int64 nTime;
616     std::string strOtherAccount;
617     std::string strComment;
618
619     CAccountingEntry()
620     {
621         SetNull();
622     }
623
624     void SetNull()
625     {
626         nCreditDebit = 0;
627         nTime = 0;
628         strAccount.clear();
629         strOtherAccount.clear();
630         strComment.clear();
631     }
632
633     IMPLEMENT_SERIALIZE
634     (
635         if (!(nType & SER_GETHASH))
636             READWRITE(nVersion);
637         // Note: strAccount is serialized as part of the key, not here.
638         READWRITE(nCreditDebit);
639         READWRITE(nTime);
640         READWRITE(strOtherAccount);
641         READWRITE(strComment);
642     )
643 };
644
645 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
646
647 #endif