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