Begin doxygen-compatible comments
[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         CRITICAL_BLOCK(cs_wallet)
215             vWalletUpdated.push_back(hashTx);
216     }
217
218     void PrintWallet(const CBlock& block);
219
220     void Inventory(const uint256 &hash)
221     {
222         CRITICAL_BLOCK(cs_wallet)
223         {
224             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
225             if (mi != mapRequestCount.end())
226                 (*mi).second++;
227         }
228     }
229
230     int GetKeyPoolSize()
231     {
232         return setKeyPool.size();
233     }
234
235     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
236
237     bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
238
239     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
240     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
241
242     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
243     bool SetMaxVersion(int nVersion);
244
245     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
246     int GetVersion() { return nWalletVersion; }
247 };
248
249 /** A key allocated from the key pool. */
250 class CReserveKey
251 {
252 protected:
253     CWallet* pwallet;
254     int64 nIndex;
255     std::vector<unsigned char> vchPubKey;
256 public:
257     CReserveKey(CWallet* pwalletIn)
258     {
259         nIndex = -1;
260         pwallet = pwalletIn;
261     }
262
263     ~CReserveKey()
264     {
265         if (!fShutdown)
266             ReturnKey();
267     }
268
269     void ReturnKey();
270     std::vector<unsigned char> GetReservedKey();
271     void KeepKey();
272 };
273
274
275 /** A transaction with a bunch of additional info that only the owner cares about. 
276  * It includes any unrecorded transactions needed to link it back to the block chain.
277  */
278 class CWalletTx : public CMerkleTx
279 {
280 private:
281     const CWallet* pwallet;
282
283 public:
284     std::vector<CMerkleTx> vtxPrev;
285     std::map<std::string, std::string> mapValue;
286     std::vector<std::pair<std::string, std::string> > vOrderForm;
287     unsigned int fTimeReceivedIsTxTime;
288     unsigned int nTimeReceived;  // time received by this node
289     char fFromMe;
290     std::string strFromAccount;
291     std::vector<char> vfSpent; // which outputs are already spent
292
293     // memory only
294     mutable char fDebitCached;
295     mutable char fCreditCached;
296     mutable char fAvailableCreditCached;
297     mutable char fChangeCached;
298     mutable int64 nDebitCached;
299     mutable int64 nCreditCached;
300     mutable int64 nAvailableCreditCached;
301     mutable int64 nChangeCached;
302
303     // memory only UI hints
304     mutable unsigned int nTimeDisplayed;
305     mutable int nLinesDisplayed;
306     mutable char fConfirmedDisplayed;
307
308     CWalletTx()
309     {
310         Init(NULL);
311     }
312
313     CWalletTx(const CWallet* pwalletIn)
314     {
315         Init(pwalletIn);
316     }
317
318     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
319     {
320         Init(pwalletIn);
321     }
322
323     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
324     {
325         Init(pwalletIn);
326     }
327
328     void Init(const CWallet* pwalletIn)
329     {
330         pwallet = pwalletIn;
331         vtxPrev.clear();
332         mapValue.clear();
333         vOrderForm.clear();
334         fTimeReceivedIsTxTime = false;
335         nTimeReceived = 0;
336         fFromMe = false;
337         strFromAccount.clear();
338         vfSpent.clear();
339         fDebitCached = false;
340         fCreditCached = false;
341         fAvailableCreditCached = false;
342         fChangeCached = false;
343         nDebitCached = 0;
344         nCreditCached = 0;
345         nAvailableCreditCached = 0;
346         nChangeCached = 0;
347         nTimeDisplayed = 0;
348         nLinesDisplayed = 0;
349         fConfirmedDisplayed = false;
350     }
351
352     IMPLEMENT_SERIALIZE
353     (
354         CWalletTx* pthis = const_cast<CWalletTx*>(this);
355         if (fRead)
356             pthis->Init(NULL);
357         char fSpent = false;
358
359         if (!fRead)
360         {
361             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
362
363             std::string str;
364             BOOST_FOREACH(char f, vfSpent)
365             {
366                 str += (f ? '1' : '0');
367                 if (f)
368                     fSpent = true;
369             }
370             pthis->mapValue["spent"] = str;
371         }
372
373         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
374         READWRITE(vtxPrev);
375         READWRITE(mapValue);
376         READWRITE(vOrderForm);
377         READWRITE(fTimeReceivedIsTxTime);
378         READWRITE(nTimeReceived);
379         READWRITE(fFromMe);
380         READWRITE(fSpent);
381
382         if (fRead)
383         {
384             pthis->strFromAccount = pthis->mapValue["fromaccount"];
385
386             if (mapValue.count("spent"))
387                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
388                     pthis->vfSpent.push_back(c != '0');
389             else
390                 pthis->vfSpent.assign(vout.size(), fSpent);
391         }
392
393         pthis->mapValue.erase("fromaccount");
394         pthis->mapValue.erase("version");
395         pthis->mapValue.erase("spent");
396     )
397
398     // marks certain txout's as spent
399     // returns true if any update took place
400     bool UpdateSpent(const std::vector<char>& vfNewSpent)
401     {
402         bool fReturn = false;
403         for (int i=0; i < vfNewSpent.size(); i++)
404         {
405             if (i == vfSpent.size())
406                 break;
407
408             if (vfNewSpent[i] && !vfSpent[i])
409             {
410                 vfSpent[i] = true;
411                 fReturn = true;
412                 fAvailableCreditCached = false;
413             }
414         }
415         return fReturn;
416     }
417
418     // make sure balances are recalculated
419     void MarkDirty()
420     {
421         fCreditCached = false;
422         fAvailableCreditCached = false;
423         fDebitCached = false;
424         fChangeCached = false;
425     }
426
427     void BindWallet(CWallet *pwalletIn)
428     {
429         pwallet = pwalletIn;
430         MarkDirty();
431     }
432
433     void MarkSpent(unsigned int nOut)
434     {
435         if (nOut >= vout.size())
436             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
437         vfSpent.resize(vout.size());
438         if (!vfSpent[nOut])
439         {
440             vfSpent[nOut] = true;
441             fAvailableCreditCached = false;
442         }
443     }
444
445     bool IsSpent(unsigned int nOut) const
446     {
447         if (nOut >= vout.size())
448             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
449         if (nOut >= vfSpent.size())
450             return false;
451         return (!!vfSpent[nOut]);
452     }
453
454     int64 GetDebit() const
455     {
456         if (vin.empty())
457             return 0;
458         if (fDebitCached)
459             return nDebitCached;
460         nDebitCached = pwallet->GetDebit(*this);
461         fDebitCached = true;
462         return nDebitCached;
463     }
464
465     int64 GetCredit(bool fUseCache=true) const
466     {
467         // Must wait until coinbase is safely deep enough in the chain before valuing it
468         if (IsCoinBase() && GetBlocksToMaturity() > 0)
469             return 0;
470
471         // GetBalance can assume transactions in mapWallet won't change
472         if (fUseCache && fCreditCached)
473             return nCreditCached;
474         nCreditCached = pwallet->GetCredit(*this);
475         fCreditCached = true;
476         return nCreditCached;
477     }
478
479     int64 GetAvailableCredit(bool fUseCache=true) const
480     {
481         // Must wait until coinbase is safely deep enough in the chain before valuing it
482         if (IsCoinBase() && GetBlocksToMaturity() > 0)
483             return 0;
484
485         if (fUseCache && fAvailableCreditCached)
486             return nAvailableCreditCached;
487
488         int64 nCredit = 0;
489         for (int i = 0; i < vout.size(); i++)
490         {
491             if (!IsSpent(i))
492             {
493                 const CTxOut &txout = vout[i];
494                 nCredit += pwallet->GetCredit(txout);
495                 if (!MoneyRange(nCredit))
496                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
497             }
498         }
499
500         nAvailableCreditCached = nCredit;
501         fAvailableCreditCached = true;
502         return nCredit;
503     }
504
505
506     int64 GetChange() const
507     {
508         if (fChangeCached)
509             return nChangeCached;
510         nChangeCached = pwallet->GetChange(*this);
511         fChangeCached = true;
512         return nChangeCached;
513     }
514
515     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
516                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
517
518     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
519                            int64& nSent, int64& nFee) const;
520
521     bool IsFromMe() const
522     {
523         return (GetDebit() > 0);
524     }
525
526     bool IsConfirmed() const
527     {
528         // Quick answer in most cases
529         if (!IsFinal())
530             return false;
531         if (GetDepthInMainChain() >= 1)
532             return true;
533         if (!IsFromMe()) // using wtx's cached debit
534             return false;
535
536         // If no confirmations but it's from us, we can still
537         // consider it confirmed if all dependencies are confirmed
538         std::map<uint256, const CMerkleTx*> mapPrev;
539         std::vector<const CMerkleTx*> vWorkQueue;
540         vWorkQueue.reserve(vtxPrev.size()+1);
541         vWorkQueue.push_back(this);
542         for (int i = 0; i < vWorkQueue.size(); i++)
543         {
544             const CMerkleTx* ptx = vWorkQueue[i];
545
546             if (!ptx->IsFinal())
547                 return false;
548             if (ptx->GetDepthInMainChain() >= 1)
549                 continue;
550             if (!pwallet->IsFromMe(*ptx))
551                 return false;
552
553             if (mapPrev.empty())
554                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
555                     mapPrev[tx.GetHash()] = &tx;
556
557             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
558             {
559                 if (!mapPrev.count(txin.prevout.hash))
560                     return false;
561                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
562             }
563         }
564         return true;
565     }
566
567     bool WriteToDisk();
568
569     int64 GetTxTime() const;
570     int GetRequestCount() const;
571
572     void AddSupportingTransactions(CTxDB& txdb);
573
574     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
575     bool AcceptWalletTransaction();
576
577     void RelayWalletTransaction(CTxDB& txdb);
578     void RelayWalletTransaction();
579 };
580
581
582 /** Private key that includes an expiration date in case it never gets used. */
583 class CWalletKey
584 {
585 public:
586     CPrivKey vchPrivKey;
587     int64 nTimeCreated;
588     int64 nTimeExpires;
589     std::string strComment;
590     //// todo: add something to note what created it (user, getnewaddress, change)
591     ////   maybe should have a map<string, string> property map
592
593     CWalletKey(int64 nExpires=0)
594     {
595         nTimeCreated = (nExpires ? GetTime() : 0);
596         nTimeExpires = nExpires;
597     }
598
599     IMPLEMENT_SERIALIZE
600     (
601         if (!(nType & SER_GETHASH))
602             READWRITE(nVersion);
603         READWRITE(vchPrivKey);
604         READWRITE(nTimeCreated);
605         READWRITE(nTimeExpires);
606         READWRITE(strComment);
607     )
608 };
609
610
611
612
613
614
615 /** Account information.
616  * Stored in wallet with key "acc"+string account name.
617  */
618 class CAccount
619 {
620 public:
621     std::vector<unsigned char> vchPubKey;
622
623     CAccount()
624     {
625         SetNull();
626     }
627
628     void SetNull()
629     {
630         vchPubKey.clear();
631     }
632
633     IMPLEMENT_SERIALIZE
634     (
635         if (!(nType & SER_GETHASH))
636             READWRITE(nVersion);
637         READWRITE(vchPubKey);
638     )
639 };
640
641
642
643 /** Internal transfers.
644  * Database key is acentry<account><counter>.
645  */
646 class CAccountingEntry
647 {
648 public:
649     std::string strAccount;
650     int64 nCreditDebit;
651     int64 nTime;
652     std::string strOtherAccount;
653     std::string strComment;
654
655     CAccountingEntry()
656     {
657         SetNull();
658     }
659
660     void SetNull()
661     {
662         nCreditDebit = 0;
663         nTime = 0;
664         strAccount.clear();
665         strOtherAccount.clear();
666         strComment.clear();
667     }
668
669     IMPLEMENT_SERIALIZE
670     (
671         if (!(nType & SER_GETHASH))
672             READWRITE(nVersion);
673         // Note: strAccount is serialized as part of the key, not here.
674         READWRITE(nCreditDebit);
675         READWRITE(nTime);
676         READWRITE(strOtherAccount);
677         READWRITE(strComment);
678     )
679 };
680
681 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
682
683 #endif