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