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