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