f9d2ea0989a91d9e90ef4f7cfb59c17c2fbc83c9
[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 "script.h"
9
10 class CWalletTx;
11 class CReserveKey;
12 class CWalletDB;
13
14 extern std::map<uint256, CWalletTx> mapWallet;
15 extern std::vector<uint256> vWalletUpdated;
16 extern CCriticalSection cs_mapWallet;
17
18 extern std::map<uint256, int> mapRequestCount;
19 extern CCriticalSection cs_mapRequestCount;
20
21 extern std::map<std::string, std::string> mapAddressBook;
22 extern CCriticalSection cs_mapAddressBook;
23
24 extern std::vector<unsigned char> vchDefaultKey;
25 extern CKey keyUser;
26
27 bool AddToWallet(const CWalletTx& wtxIn);
28 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
29 bool EraseFromWallet(uint256 hash);
30 void WalletUpdateSpent(const COutPoint& prevout);
31 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
32 void ReacceptWalletTransactions();
33 void ResendWalletTransactions();
34 int64 GetBalance();
35 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
36 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
37 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
38 bool BroadcastTransaction(CWalletTx& wtxNew);
39 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
40 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
41
42
43
44 //
45 // A transaction with a bunch of additional info that only the owner cares
46 // about.  It includes any unrecorded transactions needed to link it back
47 // to the block chain.
48 //
49 class CWalletTx : public CMerkleTx
50 {
51 public:
52     std::vector<CMerkleTx> vtxPrev;
53     std::map<std::string, std::string> mapValue;
54     std::vector<std::pair<std::string, std::string> > vOrderForm;
55     unsigned int fTimeReceivedIsTxTime;
56     unsigned int nTimeReceived;  // time received by this node
57     char fFromMe;
58     std::string strFromAccount;
59     std::vector<char> vfSpent;
60
61     // memory only
62     mutable char fDebitCached;
63     mutable char fCreditCached;
64     mutable char fAvailableCreditCached;
65     mutable char fChangeCached;
66     mutable int64 nDebitCached;
67     mutable int64 nCreditCached;
68     mutable int64 nAvailableCreditCached;
69     mutable int64 nChangeCached;
70
71     // memory only UI hints
72     mutable unsigned int nTimeDisplayed;
73     mutable int nLinesDisplayed;
74     mutable char fConfirmedDisplayed;
75
76
77     CWalletTx()
78     {
79         Init();
80     }
81
82     CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
83     {
84         Init();
85     }
86
87     CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
88     {
89         Init();
90     }
91
92     void Init()
93     {
94         vtxPrev.clear();
95         mapValue.clear();
96         vOrderForm.clear();
97         fTimeReceivedIsTxTime = false;
98         nTimeReceived = 0;
99         fFromMe = false;
100         strFromAccount.clear();
101         vfSpent.clear();
102         fDebitCached = false;
103         fCreditCached = false;
104         fAvailableCreditCached = false;
105         fChangeCached = false;
106         nDebitCached = 0;
107         nCreditCached = 0;
108         nAvailableCreditCached = 0;
109         nChangeCached = 0;
110         nTimeDisplayed = 0;
111         nLinesDisplayed = 0;
112         fConfirmedDisplayed = false;
113     }
114
115     IMPLEMENT_SERIALIZE
116     (
117         CWalletTx* pthis = const_cast<CWalletTx*>(this);
118         if (fRead)
119             pthis->Init();
120         char fSpent = false;
121
122         if (!fRead)
123         {
124             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
125
126             std::string str;
127             BOOST_FOREACH(char f, vfSpent)
128             {
129                 str += (f ? '1' : '0');
130                 if (f)
131                     fSpent = true;
132             }
133             pthis->mapValue["spent"] = str;
134         }
135
136         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
137         READWRITE(vtxPrev);
138         READWRITE(mapValue);
139         READWRITE(vOrderForm);
140         READWRITE(fTimeReceivedIsTxTime);
141         READWRITE(nTimeReceived);
142         READWRITE(fFromMe);
143         READWRITE(fSpent);
144
145         if (fRead)
146         {
147             pthis->strFromAccount = pthis->mapValue["fromaccount"];
148
149             if (mapValue.count("spent"))
150                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
151                     pthis->vfSpent.push_back(c != '0');
152             else
153                 pthis->vfSpent.assign(vout.size(), fSpent);
154         }
155
156         pthis->mapValue.erase("fromaccount");
157         pthis->mapValue.erase("version");
158         pthis->mapValue.erase("spent");
159     )
160
161     // marks certain txout's as spent
162     // returns true if any update took place
163     bool UpdateSpent(const std::vector<char>& vfNewSpent)
164     {
165         bool fReturn = false;
166         for (int i=0; i < vfNewSpent.size(); i++)
167         {
168             if (i == vfSpent.size())
169                 break;
170
171             if (vfNewSpent[i] && !vfSpent[i])
172             {
173                 vfSpent[i] = true;
174                 fReturn = true;
175                 fAvailableCreditCached = false;
176             }
177         }
178         return fReturn;
179     }
180
181     void MarkDirty()
182     {
183         fCreditCached = false;
184         fAvailableCreditCached = false;
185         fDebitCached = false;
186         fChangeCached = false;
187     }
188
189     void MarkSpent(unsigned int nOut)
190     {
191         if (nOut >= vout.size())
192             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
193         vfSpent.resize(vout.size());
194         if (!vfSpent[nOut])
195         {
196             vfSpent[nOut] = true;
197             fAvailableCreditCached = false;
198         }
199     }
200
201     bool IsSpent(unsigned int nOut) const
202     {
203         if (nOut >= vout.size())
204             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
205         if (nOut >= vfSpent.size())
206             return false;
207         return (!!vfSpent[nOut]);
208     }
209
210     int64 GetDebit() const
211     {
212         if (vin.empty())
213             return 0;
214         if (fDebitCached)
215             return nDebitCached;
216         nDebitCached = CTransaction::GetDebit();
217         fDebitCached = true;
218         return nDebitCached;
219     }
220
221     int64 GetCredit(bool fUseCache=true) const
222     {
223         // Must wait until coinbase is safely deep enough in the chain before valuing it
224         if (IsCoinBase() && GetBlocksToMaturity() > 0)
225             return 0;
226
227         // GetBalance can assume transactions in mapWallet won't change
228         if (fUseCache && fCreditCached)
229             return nCreditCached;
230         nCreditCached = CTransaction::GetCredit();
231         fCreditCached = true;
232         return nCreditCached;
233     }
234
235     int64 GetAvailableCredit(bool fUseCache=true) const
236     {
237         // Must wait until coinbase is safely deep enough in the chain before valuing it
238         if (IsCoinBase() && GetBlocksToMaturity() > 0)
239             return 0;
240
241         if (fUseCache && fAvailableCreditCached)
242             return nAvailableCreditCached;
243
244         int64 nCredit = 0;
245         for (int i = 0; i < vout.size(); i++)
246         {
247             if (!IsSpent(i))
248             {
249                 const CTxOut &txout = vout[i];
250                 nCredit += txout.GetCredit();
251                 if (!MoneyRange(nCredit))
252                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
253             }
254         }
255
256         nAvailableCreditCached = nCredit;
257         fAvailableCreditCached = true;
258         return nCredit;
259     }
260
261
262     int64 GetChange() const
263     {
264         if (fChangeCached)
265             return nChangeCached;
266         nChangeCached = CTransaction::GetChange();
267         fChangeCached = true;
268         return nChangeCached;
269     }
270
271     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
272                     std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
273
274     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
275                            int64& nSent, int64& nFee) const;
276
277     bool IsFromMe() const
278     {
279         return (GetDebit() > 0);
280     }
281
282     bool IsConfirmed() const
283     {
284         // Quick answer in most cases
285         if (!IsFinal())
286             return false;
287         if (GetDepthInMainChain() >= 1)
288             return true;
289         if (!IsFromMe()) // using wtx's cached debit
290             return false;
291
292         // If no confirmations but it's from us, we can still
293         // consider it confirmed if all dependencies are confirmed
294         std::map<uint256, const CMerkleTx*> mapPrev;
295         std::vector<const CMerkleTx*> vWorkQueue;
296         vWorkQueue.reserve(vtxPrev.size()+1);
297         vWorkQueue.push_back(this);
298         for (int i = 0; i < vWorkQueue.size(); i++)
299         {
300             const CMerkleTx* ptx = vWorkQueue[i];
301
302             if (!ptx->IsFinal())
303                 return false;
304             if (ptx->GetDepthInMainChain() >= 1)
305                 continue;
306             if (!ptx->IsFromMe())
307                 return false;
308
309             if (mapPrev.empty())
310                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
311                     mapPrev[tx.GetHash()] = &tx;
312
313             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
314             {
315                 if (!mapPrev.count(txin.prevout.hash))
316                     return false;
317                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
318             }
319         }
320         return true;
321     }
322
323     bool WriteToDisk();
324
325     int64 GetTxTime() const;
326     int GetRequestCount() const;
327
328     void AddSupportingTransactions(CTxDB& txdb);
329
330     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
331     bool AcceptWalletTransaction();
332
333     void RelayWalletTransaction(CTxDB& txdb);
334     void RelayWalletTransaction();
335 };
336
337
338 //
339 // Private key that includes an expiration date in case it never gets used.
340 //
341 class CWalletKey
342 {
343 public:
344     CPrivKey vchPrivKey;
345     int64 nTimeCreated;
346     int64 nTimeExpires;
347     std::string strComment;
348     //// todo: add something to note what created it (user, getnewaddress, change)
349     ////   maybe should have a map<string, string> property map
350
351     CWalletKey(int64 nExpires=0)
352     {
353         nTimeCreated = (nExpires ? GetTime() : 0);
354         nTimeExpires = nExpires;
355     }
356
357     IMPLEMENT_SERIALIZE
358     (
359         if (!(nType & SER_GETHASH))
360             READWRITE(nVersion);
361         READWRITE(vchPrivKey);
362         READWRITE(nTimeCreated);
363         READWRITE(nTimeExpires);
364         READWRITE(strComment);
365     )
366 };
367
368
369
370
371
372
373 //
374 // Account information.
375 // Stored in wallet with key "acc"+string account name
376 //
377 class CAccount
378 {
379 public:
380     std::vector<unsigned char> vchPubKey;
381
382     CAccount()
383     {
384         SetNull();
385     }
386
387     void SetNull()
388     {
389         vchPubKey.clear();
390     }
391
392     IMPLEMENT_SERIALIZE
393     (
394         if (!(nType & SER_GETHASH))
395             READWRITE(nVersion);
396         READWRITE(vchPubKey);
397     )
398 };
399
400
401
402 //
403 // Internal transfers.
404 // Database key is acentry<account><counter>
405 //
406 class CAccountingEntry
407 {
408 public:
409     std::string strAccount;
410     int64 nCreditDebit;
411     int64 nTime;
412     std::string strOtherAccount;
413     std::string strComment;
414
415     CAccountingEntry()
416     {
417         SetNull();
418     }
419
420     void SetNull()
421     {
422         nCreditDebit = 0;
423         nTime = 0;
424         strAccount.clear();
425         strOtherAccount.clear();
426         strComment.clear();
427     }
428
429     IMPLEMENT_SERIALIZE
430     (
431         if (!(nType & SER_GETHASH))
432             READWRITE(nVersion);
433         // Note: strAccount is serialized as part of the key, not here.
434         READWRITE(nCreditDebit);
435         READWRITE(nTime);
436         READWRITE(strOtherAccount);
437         READWRITE(strComment);
438     )
439 };
440
441 #endif