change type of various bare chars to bool that are only used as bool (and never seria...
[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 "main.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 /** (client) version numbers for particular wallet features */
18 enum WalletFeature
19 {
20     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
21
22     FEATURE_WALLETCRYPT = 40000, // wallet encryption
23     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
24
25     FEATURE_LATEST = 60000
26 };
27
28
29 /** A key pool entry */
30 class CKeyPool
31 {
32 public:
33     int64 nTime;
34     std::vector<unsigned char> vchPubKey;
35
36     CKeyPool()
37     {
38         nTime = GetTime();
39     }
40
41     CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
42     {
43         nTime = GetTime();
44         vchPubKey = vchPubKeyIn;
45     }
46
47     IMPLEMENT_SERIALIZE
48     (
49         if (!(nType & SER_GETHASH))
50             READWRITE(nVersion);
51         READWRITE(nTime);
52         READWRITE(vchPubKey);
53     )
54 };
55
56 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
57  * and provides the ability to create new transactions.
58  */
59 class CWallet : public CCryptoKeyStore
60 {
61 private:
62     bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
63     bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
64
65     CWalletDB *pwalletdbEncryption;
66
67     // the current wallet version: clients below this version are not able to load the wallet
68     int nWalletVersion;
69
70     // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
71     int nWalletMaxVersion;
72
73 public:
74     mutable CCriticalSection cs_wallet;
75
76     bool fFileBacked;
77     std::string strWalletFile;
78
79     std::set<int64> setKeyPool;
80
81
82     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
83     MasterKeyMap mapMasterKeys;
84     unsigned int nMasterKeyMaxID;
85
86     CWallet()
87     {
88         nWalletVersion = FEATURE_BASE;
89         nWalletMaxVersion = FEATURE_BASE;
90         fFileBacked = false;
91         nMasterKeyMaxID = 0;
92         pwalletdbEncryption = NULL;
93     }
94     CWallet(std::string strWalletFileIn)
95     {
96         nWalletVersion = FEATURE_BASE;
97         nWalletMaxVersion = FEATURE_BASE;
98         strWalletFile = strWalletFileIn;
99         fFileBacked = true;
100         nMasterKeyMaxID = 0;
101         pwalletdbEncryption = NULL;
102     }
103
104     std::map<uint256, CWalletTx> mapWallet;
105     std::vector<uint256> vWalletUpdated;
106
107     std::map<uint256, int> mapRequestCount;
108
109     std::map<CBitcoinAddress, std::string> mapAddressBook;
110
111     std::vector<unsigned char> vchDefaultKey;
112
113     // check whether we are allowed to upgrade (or already support) to the named feature
114     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
115
116     // keystore implementation
117     // Generate a new key
118     std::vector<unsigned char> GenerateNewKey();
119     // Adds a key to the store, and saves it to disk.
120     bool AddKey(const CKey& key);
121     // Adds a key to the store, without saving it to disk (used by LoadWallet)
122     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
123
124     bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
125
126     // Adds an encrypted key to the store, and saves it to disk.
127     bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
128     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
129     bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
130     bool AddCScript(const CScript& redeemScript);
131     bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
132
133     bool Unlock(const SecureString& strWalletPassphrase);
134     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
135     bool EncryptWallet(const SecureString& strWalletPassphrase);
136
137     void MarkDirty();
138     bool AddToWallet(const CWalletTx& wtxIn);
139     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
140     bool EraseFromWallet(uint256 hash);
141     void WalletUpdateSpent(const CTransaction& prevout);
142     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
143     int ScanForWalletTransaction(const uint256& hashTx);
144     void ReacceptWalletTransactions();
145     void ResendWalletTransactions();
146     int64 GetBalance() const;
147     int64 GetUnconfirmedBalance() const;
148     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
149     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
150     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
151     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
152     std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
153
154     bool NewKeyPool();
155     bool TopUpKeyPool();
156     int64 AddReserveKey(const CKeyPool& keypool);
157     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
158     void KeepKey(int64 nIndex);
159     void ReturnKey(int64 nIndex);
160     bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
161     int64 GetOldestKeyPoolTime();
162     void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
163
164     bool IsMine(const CTxIn& txin) const;
165     int64 GetDebit(const CTxIn& txin) const;
166     bool IsMine(const CTxOut& txout) const
167     {
168         return ::IsMine(*this, txout.scriptPubKey);
169     }
170     int64 GetCredit(const CTxOut& txout) const
171     {
172         if (!MoneyRange(txout.nValue))
173             throw std::runtime_error("CWallet::GetCredit() : value out of range");
174         return (IsMine(txout) ? txout.nValue : 0);
175     }
176     bool IsChange(const CTxOut& txout) const;
177     int64 GetChange(const CTxOut& txout) const
178     {
179         if (!MoneyRange(txout.nValue))
180             throw std::runtime_error("CWallet::GetChange() : value out of range");
181         return (IsChange(txout) ? txout.nValue : 0);
182     }
183     bool IsMine(const CTransaction& tx) const
184     {
185         BOOST_FOREACH(const CTxOut& txout, tx.vout)
186             if (IsMine(txout))
187                 return true;
188         return false;
189     }
190     bool IsFromMe(const CTransaction& tx) const
191     {
192         return (GetDebit(tx) > 0);
193     }
194     int64 GetDebit(const CTransaction& tx) const
195     {
196         int64 nDebit = 0;
197         BOOST_FOREACH(const CTxIn& txin, tx.vin)
198         {
199             nDebit += GetDebit(txin);
200             if (!MoneyRange(nDebit))
201                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
202         }
203         return nDebit;
204     }
205     int64 GetCredit(const CTransaction& tx) const
206     {
207         int64 nCredit = 0;
208         BOOST_FOREACH(const CTxOut& txout, tx.vout)
209         {
210             nCredit += GetCredit(txout);
211             if (!MoneyRange(nCredit))
212                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
213         }
214         return nCredit;
215     }
216     int64 GetChange(const CTransaction& tx) const
217     {
218         int64 nChange = 0;
219         BOOST_FOREACH(const CTxOut& txout, tx.vout)
220         {
221             nChange += GetChange(txout);
222             if (!MoneyRange(nChange))
223                 throw std::runtime_error("CWallet::GetChange() : value out of range");
224         }
225         return nChange;
226     }
227     void SetBestChain(const CBlockLocator& loc);
228
229     int LoadWallet(bool& fFirstRunRet);
230 //    bool BackupWallet(const std::string& strDest);
231
232     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
233
234     bool DelAddressBookName(const CBitcoinAddress& address);
235
236     void UpdatedTransaction(const uint256 &hashTx)
237     {
238         {
239             LOCK(cs_wallet);
240             vWalletUpdated.push_back(hashTx);
241         }
242     }
243
244     void PrintWallet(const CBlock& block);
245
246     void Inventory(const uint256 &hash)
247     {
248         {
249             LOCK(cs_wallet);
250             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
251             if (mi != mapRequestCount.end())
252                 (*mi).second++;
253         }
254     }
255
256     int GetKeyPoolSize()
257     {
258         return setKeyPool.size();
259     }
260
261     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
262
263     bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
264
265     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
266     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
267
268     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
269     bool SetMaxVersion(int nVersion);
270
271     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
272     int GetVersion() { return nWalletVersion; }
273 };
274
275 /** A key allocated from the key pool. */
276 class CReserveKey
277 {
278 protected:
279     CWallet* pwallet;
280     int64 nIndex;
281     std::vector<unsigned char> vchPubKey;
282 public:
283     CReserveKey(CWallet* pwalletIn)
284     {
285         nIndex = -1;
286         pwallet = pwalletIn;
287     }
288
289     ~CReserveKey()
290     {
291         if (!fShutdown)
292             ReturnKey();
293     }
294
295     void ReturnKey();
296     std::vector<unsigned char> GetReservedKey();
297     void KeepKey();
298 };
299
300
301 /** A transaction with a bunch of additional info that only the owner cares about. 
302  * It includes any unrecorded transactions needed to link it back to the block chain.
303  */
304 class CWalletTx : public CMerkleTx
305 {
306 private:
307     const CWallet* pwallet;
308
309 public:
310     std::vector<CMerkleTx> vtxPrev;
311     std::map<std::string, std::string> mapValue;
312     std::vector<std::pair<std::string, std::string> > vOrderForm;
313     unsigned int fTimeReceivedIsTxTime;
314     unsigned int nTimeReceived;  // time received by this node
315     char fFromMe;
316     std::string strFromAccount;
317     std::vector<char> vfSpent; // which outputs are already spent
318
319     // memory only
320     mutable bool fDebitCached;
321     mutable bool fCreditCached;
322     mutable bool fAvailableCreditCached;
323     mutable bool fChangeCached;
324     mutable int64 nDebitCached;
325     mutable int64 nCreditCached;
326     mutable int64 nAvailableCreditCached;
327     mutable int64 nChangeCached;
328
329     // memory only UI hints
330     mutable unsigned int nTimeDisplayed;
331     mutable int nLinesDisplayed;
332     mutable char fConfirmedDisplayed;
333
334     CWalletTx()
335     {
336         Init(NULL);
337     }
338
339     CWalletTx(const CWallet* pwalletIn)
340     {
341         Init(pwalletIn);
342     }
343
344     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
345     {
346         Init(pwalletIn);
347     }
348
349     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
350     {
351         Init(pwalletIn);
352     }
353
354     void Init(const CWallet* pwalletIn)
355     {
356         pwallet = pwalletIn;
357         vtxPrev.clear();
358         mapValue.clear();
359         vOrderForm.clear();
360         fTimeReceivedIsTxTime = false;
361         nTimeReceived = 0;
362         fFromMe = false;
363         strFromAccount.clear();
364         vfSpent.clear();
365         fDebitCached = false;
366         fCreditCached = false;
367         fAvailableCreditCached = false;
368         fChangeCached = false;
369         nDebitCached = 0;
370         nCreditCached = 0;
371         nAvailableCreditCached = 0;
372         nChangeCached = 0;
373         nTimeDisplayed = 0;
374         nLinesDisplayed = 0;
375         fConfirmedDisplayed = false;
376     }
377
378     IMPLEMENT_SERIALIZE
379     (
380         CWalletTx* pthis = const_cast<CWalletTx*>(this);
381         if (fRead)
382             pthis->Init(NULL);
383         char fSpent = false;
384
385         if (!fRead)
386         {
387             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
388
389             std::string str;
390             BOOST_FOREACH(char f, vfSpent)
391             {
392                 str += (f ? '1' : '0');
393                 if (f)
394                     fSpent = true;
395             }
396             pthis->mapValue["spent"] = str;
397         }
398
399         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
400         READWRITE(vtxPrev);
401         READWRITE(mapValue);
402         READWRITE(vOrderForm);
403         READWRITE(fTimeReceivedIsTxTime);
404         READWRITE(nTimeReceived);
405         READWRITE(fFromMe);
406         READWRITE(fSpent);
407
408         if (fRead)
409         {
410             pthis->strFromAccount = pthis->mapValue["fromaccount"];
411
412             if (mapValue.count("spent"))
413                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
414                     pthis->vfSpent.push_back(c != '0');
415             else
416                 pthis->vfSpent.assign(vout.size(), fSpent);
417         }
418
419         pthis->mapValue.erase("fromaccount");
420         pthis->mapValue.erase("version");
421         pthis->mapValue.erase("spent");
422     )
423
424     // marks certain txout's as spent
425     // returns true if any update took place
426     bool UpdateSpent(const std::vector<char>& vfNewSpent)
427     {
428         bool fReturn = false;
429         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
430         {
431             if (i == vfSpent.size())
432                 break;
433
434             if (vfNewSpent[i] && !vfSpent[i])
435             {
436                 vfSpent[i] = true;
437                 fReturn = true;
438                 fAvailableCreditCached = false;
439             }
440         }
441         return fReturn;
442     }
443
444     // make sure balances are recalculated
445     void MarkDirty()
446     {
447         fCreditCached = false;
448         fAvailableCreditCached = false;
449         fDebitCached = false;
450         fChangeCached = false;
451     }
452
453     void BindWallet(CWallet *pwalletIn)
454     {
455         pwallet = pwalletIn;
456         MarkDirty();
457     }
458
459     void MarkSpent(unsigned int nOut)
460     {
461         if (nOut >= vout.size())
462             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
463         vfSpent.resize(vout.size());
464         if (!vfSpent[nOut])
465         {
466             vfSpent[nOut] = true;
467             fAvailableCreditCached = false;
468         }
469     }
470
471     bool IsSpent(unsigned int nOut) const
472     {
473         if (nOut >= vout.size())
474             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
475         if (nOut >= vfSpent.size())
476             return false;
477         return (!!vfSpent[nOut]);
478     }
479
480     int64 GetDebit() const
481     {
482         if (vin.empty())
483             return 0;
484         if (fDebitCached)
485             return nDebitCached;
486         nDebitCached = pwallet->GetDebit(*this);
487         fDebitCached = true;
488         return nDebitCached;
489     }
490
491     int64 GetCredit(bool fUseCache=true) const
492     {
493         // Must wait until coinbase is safely deep enough in the chain before valuing it
494         if (IsCoinBase() && GetBlocksToMaturity() > 0)
495             return 0;
496
497         // GetBalance can assume transactions in mapWallet won't change
498         if (fUseCache && fCreditCached)
499             return nCreditCached;
500         nCreditCached = pwallet->GetCredit(*this);
501         fCreditCached = true;
502         return nCreditCached;
503     }
504
505     int64 GetAvailableCredit(bool fUseCache=true) const
506     {
507         // Must wait until coinbase is safely deep enough in the chain before valuing it
508         if (IsCoinBase() && GetBlocksToMaturity() > 0)
509             return 0;
510
511         if (fUseCache && fAvailableCreditCached)
512             return nAvailableCreditCached;
513
514         int64 nCredit = 0;
515         for (unsigned int i = 0; i < vout.size(); i++)
516         {
517             if (!IsSpent(i))
518             {
519                 const CTxOut &txout = vout[i];
520                 nCredit += pwallet->GetCredit(txout);
521                 if (!MoneyRange(nCredit))
522                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
523             }
524         }
525
526         nAvailableCreditCached = nCredit;
527         fAvailableCreditCached = true;
528         return nCredit;
529     }
530
531
532     int64 GetChange() const
533     {
534         if (fChangeCached)
535             return nChangeCached;
536         nChangeCached = pwallet->GetChange(*this);
537         fChangeCached = true;
538         return nChangeCached;
539     }
540
541     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
542                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
543
544     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
545                            int64& nSent, int64& nFee) const;
546
547     bool IsFromMe() const
548     {
549         return (GetDebit() > 0);
550     }
551
552     bool IsConfirmed() const
553     {
554         // Quick answer in most cases
555         if (!IsFinal())
556             return false;
557         if (GetDepthInMainChain() >= 1)
558             return true;
559         if (!IsFromMe()) // using wtx's cached debit
560             return false;
561
562         // If no confirmations but it's from us, we can still
563         // consider it confirmed if all dependencies are confirmed
564         std::map<uint256, const CMerkleTx*> mapPrev;
565         std::vector<const CMerkleTx*> vWorkQueue;
566         vWorkQueue.reserve(vtxPrev.size()+1);
567         vWorkQueue.push_back(this);
568         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
569         {
570             const CMerkleTx* ptx = vWorkQueue[i];
571
572             if (!ptx->IsFinal())
573                 return false;
574             if (ptx->GetDepthInMainChain() >= 1)
575                 continue;
576             if (!pwallet->IsFromMe(*ptx))
577                 return false;
578
579             if (mapPrev.empty())
580             {
581                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
582                     mapPrev[tx.GetHash()] = &tx;
583             }
584
585             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
586             {
587                 if (!mapPrev.count(txin.prevout.hash))
588                     return false;
589                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
590             }
591         }
592         return true;
593     }
594
595     bool WriteToDisk();
596
597     int64 GetTxTime() const;
598     int GetRequestCount() const;
599
600     void AddSupportingTransactions(CTxDB& txdb);
601
602     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
603     bool AcceptWalletTransaction();
604
605     void RelayWalletTransaction(CTxDB& txdb);
606     void RelayWalletTransaction();
607 };
608
609
610 /** Private key that includes an expiration date in case it never gets used. */
611 class CWalletKey
612 {
613 public:
614     CPrivKey vchPrivKey;
615     int64 nTimeCreated;
616     int64 nTimeExpires;
617     std::string strComment;
618     //// todo: add something to note what created it (user, getnewaddress, change)
619     ////   maybe should have a map<string, string> property map
620
621     CWalletKey(int64 nExpires=0)
622     {
623         nTimeCreated = (nExpires ? GetTime() : 0);
624         nTimeExpires = nExpires;
625     }
626
627     IMPLEMENT_SERIALIZE
628     (
629         if (!(nType & SER_GETHASH))
630             READWRITE(nVersion);
631         READWRITE(vchPrivKey);
632         READWRITE(nTimeCreated);
633         READWRITE(nTimeExpires);
634         READWRITE(strComment);
635     )
636 };
637
638
639
640
641
642
643 /** Account information.
644  * Stored in wallet with key "acc"+string account name.
645  */
646 class CAccount
647 {
648 public:
649     std::vector<unsigned char> vchPubKey;
650
651     CAccount()
652     {
653         SetNull();
654     }
655
656     void SetNull()
657     {
658         vchPubKey.clear();
659     }
660
661     IMPLEMENT_SERIALIZE
662     (
663         if (!(nType & SER_GETHASH))
664             READWRITE(nVersion);
665         READWRITE(vchPubKey);
666     )
667 };
668
669
670
671 /** Internal transfers.
672  * Database key is acentry<account><counter>.
673  */
674 class CAccountingEntry
675 {
676 public:
677     std::string strAccount;
678     int64 nCreditDebit;
679     int64 nTime;
680     std::string strOtherAccount;
681     std::string strComment;
682
683     CAccountingEntry()
684     {
685         SetNull();
686     }
687
688     void SetNull()
689     {
690         nCreditDebit = 0;
691         nTime = 0;
692         strAccount.clear();
693         strOtherAccount.clear();
694         strComment.clear();
695     }
696
697     IMPLEMENT_SERIALIZE
698     (
699         if (!(nType & SER_GETHASH))
700             READWRITE(nVersion);
701         // Note: strAccount is serialized as part of the key, not here.
702         READWRITE(nCreditDebit);
703         READWRITE(nTime);
704         READWRITE(strOtherAccount);
705         READWRITE(strComment);
706     )
707 };
708
709 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
710
711 #endif