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