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