Remove no-longer used UI hints in bitcoin core
[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     CWalletTx()
330     {
331         Init(NULL);
332     }
333
334     CWalletTx(const CWallet* pwalletIn)
335     {
336         Init(pwalletIn);
337     }
338
339     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
340     {
341         Init(pwalletIn);
342     }
343
344     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
345     {
346         Init(pwalletIn);
347     }
348
349     void Init(const CWallet* pwalletIn)
350     {
351         pwallet = pwalletIn;
352         vtxPrev.clear();
353         mapValue.clear();
354         vOrderForm.clear();
355         fTimeReceivedIsTxTime = false;
356         nTimeReceived = 0;
357         fFromMe = false;
358         strFromAccount.clear();
359         vfSpent.clear();
360         fDebitCached = false;
361         fCreditCached = false;
362         fAvailableCreditCached = false;
363         fChangeCached = false;
364         nDebitCached = 0;
365         nCreditCached = 0;
366         nAvailableCreditCached = 0;
367         nChangeCached = 0;
368     }
369
370     IMPLEMENT_SERIALIZE
371     (
372         CWalletTx* pthis = const_cast<CWalletTx*>(this);
373         if (fRead)
374             pthis->Init(NULL);
375         char fSpent = false;
376
377         if (!fRead)
378         {
379             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
380
381             std::string str;
382             BOOST_FOREACH(char f, vfSpent)
383             {
384                 str += (f ? '1' : '0');
385                 if (f)
386                     fSpent = true;
387             }
388             pthis->mapValue["spent"] = str;
389         }
390
391         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
392         READWRITE(vtxPrev);
393         READWRITE(mapValue);
394         READWRITE(vOrderForm);
395         READWRITE(fTimeReceivedIsTxTime);
396         READWRITE(nTimeReceived);
397         READWRITE(fFromMe);
398         READWRITE(fSpent);
399
400         if (fRead)
401         {
402             pthis->strFromAccount = pthis->mapValue["fromaccount"];
403
404             if (mapValue.count("spent"))
405                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
406                     pthis->vfSpent.push_back(c != '0');
407             else
408                 pthis->vfSpent.assign(vout.size(), fSpent);
409         }
410
411         pthis->mapValue.erase("fromaccount");
412         pthis->mapValue.erase("version");
413         pthis->mapValue.erase("spent");
414     )
415
416     // marks certain txout's as spent
417     // returns true if any update took place
418     bool UpdateSpent(const std::vector<char>& vfNewSpent)
419     {
420         bool fReturn = false;
421         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
422         {
423             if (i == vfSpent.size())
424                 break;
425
426             if (vfNewSpent[i] && !vfSpent[i])
427             {
428                 vfSpent[i] = true;
429                 fReturn = true;
430                 fAvailableCreditCached = false;
431             }
432         }
433         return fReturn;
434     }
435
436     // make sure balances are recalculated
437     void MarkDirty()
438     {
439         fCreditCached = false;
440         fAvailableCreditCached = false;
441         fDebitCached = false;
442         fChangeCached = false;
443     }
444
445     void BindWallet(CWallet *pwalletIn)
446     {
447         pwallet = pwalletIn;
448         MarkDirty();
449     }
450
451     void MarkSpent(unsigned int nOut)
452     {
453         if (nOut >= vout.size())
454             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
455         vfSpent.resize(vout.size());
456         if (!vfSpent[nOut])
457         {
458             vfSpent[nOut] = true;
459             fAvailableCreditCached = false;
460         }
461     }
462
463     bool IsSpent(unsigned int nOut) const
464     {
465         if (nOut >= vout.size())
466             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
467         if (nOut >= vfSpent.size())
468             return false;
469         return (!!vfSpent[nOut]);
470     }
471
472     int64 GetDebit() const
473     {
474         if (vin.empty())
475             return 0;
476         if (fDebitCached)
477             return nDebitCached;
478         nDebitCached = pwallet->GetDebit(*this);
479         fDebitCached = true;
480         return nDebitCached;
481     }
482
483     int64 GetCredit(bool fUseCache=true) const
484     {
485         // Must wait until coinbase is safely deep enough in the chain before valuing it
486         if (IsCoinBase() && GetBlocksToMaturity() > 0)
487             return 0;
488
489         // GetBalance can assume transactions in mapWallet won't change
490         if (fUseCache && fCreditCached)
491             return nCreditCached;
492         nCreditCached = pwallet->GetCredit(*this);
493         fCreditCached = true;
494         return nCreditCached;
495     }
496
497     int64 GetAvailableCredit(bool fUseCache=true) const
498     {
499         // Must wait until coinbase is safely deep enough in the chain before valuing it
500         if (IsCoinBase() && GetBlocksToMaturity() > 0)
501             return 0;
502
503         if (fUseCache && fAvailableCreditCached)
504             return nAvailableCreditCached;
505
506         int64 nCredit = 0;
507         for (unsigned int i = 0; i < vout.size(); i++)
508         {
509             if (!IsSpent(i))
510             {
511                 const CTxOut &txout = vout[i];
512                 nCredit += pwallet->GetCredit(txout);
513                 if (!MoneyRange(nCredit))
514                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
515             }
516         }
517
518         nAvailableCreditCached = nCredit;
519         fAvailableCreditCached = true;
520         return nCredit;
521     }
522
523
524     int64 GetChange() const
525     {
526         if (fChangeCached)
527             return nChangeCached;
528         nChangeCached = pwallet->GetChange(*this);
529         fChangeCached = true;
530         return nChangeCached;
531     }
532
533     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
534                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
535
536     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
537                            int64& nSent, int64& nFee) const;
538
539     bool IsFromMe() const
540     {
541         return (GetDebit() > 0);
542     }
543
544     bool IsConfirmed() const
545     {
546         // Quick answer in most cases
547         if (!IsFinal())
548             return false;
549         if (GetDepthInMainChain() >= 1)
550             return true;
551         if (!IsFromMe()) // using wtx's cached debit
552             return false;
553
554         // If no confirmations but it's from us, we can still
555         // consider it confirmed if all dependencies are confirmed
556         std::map<uint256, const CMerkleTx*> mapPrev;
557         std::vector<const CMerkleTx*> vWorkQueue;
558         vWorkQueue.reserve(vtxPrev.size()+1);
559         vWorkQueue.push_back(this);
560         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
561         {
562             const CMerkleTx* ptx = vWorkQueue[i];
563
564             if (!ptx->IsFinal())
565                 return false;
566             if (ptx->GetDepthInMainChain() >= 1)
567                 continue;
568             if (!pwallet->IsFromMe(*ptx))
569                 return false;
570
571             if (mapPrev.empty())
572             {
573                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
574                     mapPrev[tx.GetHash()] = &tx;
575             }
576
577             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
578             {
579                 if (!mapPrev.count(txin.prevout.hash))
580                     return false;
581                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
582             }
583         }
584         return true;
585     }
586
587     bool WriteToDisk();
588
589     int64 GetTxTime() const;
590     int GetRequestCount() const;
591
592     void AddSupportingTransactions(CTxDB& txdb);
593
594     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
595     bool AcceptWalletTransaction();
596
597     void RelayWalletTransaction(CTxDB& txdb);
598     void RelayWalletTransaction();
599 };
600
601
602 /** Private key that includes an expiration date in case it never gets used. */
603 class CWalletKey
604 {
605 public:
606     CPrivKey vchPrivKey;
607     int64 nTimeCreated;
608     int64 nTimeExpires;
609     std::string strComment;
610     //// todo: add something to note what created it (user, getnewaddress, change)
611     ////   maybe should have a map<string, string> property map
612
613     CWalletKey(int64 nExpires=0)
614     {
615         nTimeCreated = (nExpires ? GetTime() : 0);
616         nTimeExpires = nExpires;
617     }
618
619     IMPLEMENT_SERIALIZE
620     (
621         if (!(nType & SER_GETHASH))
622             READWRITE(nVersion);
623         READWRITE(vchPrivKey);
624         READWRITE(nTimeCreated);
625         READWRITE(nTimeExpires);
626         READWRITE(strComment);
627     )
628 };
629
630
631
632
633
634
635 /** Account information.
636  * Stored in wallet with key "acc"+string account name.
637  */
638 class CAccount
639 {
640 public:
641     std::vector<unsigned char> vchPubKey;
642
643     CAccount()
644     {
645         SetNull();
646     }
647
648     void SetNull()
649     {
650         vchPubKey.clear();
651     }
652
653     IMPLEMENT_SERIALIZE
654     (
655         if (!(nType & SER_GETHASH))
656             READWRITE(nVersion);
657         READWRITE(vchPubKey);
658     )
659 };
660
661
662
663 /** Internal transfers.
664  * Database key is acentry<account><counter>.
665  */
666 class CAccountingEntry
667 {
668 public:
669     std::string strAccount;
670     int64 nCreditDebit;
671     int64 nTime;
672     std::string strOtherAccount;
673     std::string strComment;
674
675     CAccountingEntry()
676     {
677         SetNull();
678     }
679
680     void SetNull()
681     {
682         nCreditDebit = 0;
683         nTime = 0;
684         strAccount.clear();
685         strOtherAccount.clear();
686         strComment.clear();
687     }
688
689     IMPLEMENT_SERIALIZE
690     (
691         if (!(nType & SER_GETHASH))
692             READWRITE(nVersion);
693         // Note: strAccount is serialized as part of the key, not here.
694         READWRITE(nCreditDebit);
695         READWRITE(nTime);
696         READWRITE(strOtherAccount);
697         READWRITE(strComment);
698     )
699 };
700
701 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
702
703 #endif