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