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