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