]> Git Repo - VerusCoin.git/blob - src/wallet.h
qt: Handle address purpose in incremental updates
[VerusCoin.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 COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
7
8 #include "walletdb.h"
9
10 #include <string>
11 #include <vector>
12
13 #include <stdlib.h>
14
15 #include "main.h"
16 #include "key.h"
17 #include "keystore.h"
18 #include "script.h"
19 #include "ui_interface.h"
20 #include "util.h"
21
22 class CAccountingEntry;
23 class CWalletTx;
24 class CReserveKey;
25 class COutput;
26 class CWalletDB;
27
28 /** (client) version numbers for particular wallet features */
29 enum WalletFeature
30 {
31     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
32
33     FEATURE_WALLETCRYPT = 40000, // wallet encryption
34     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
35
36     FEATURE_LATEST = 60000
37 };
38
39
40 /** A key pool entry */
41 class CKeyPool
42 {
43 public:
44     int64 nTime;
45     CPubKey vchPubKey;
46
47     CKeyPool()
48     {
49         nTime = GetTime();
50     }
51
52     CKeyPool(const CPubKey& vchPubKeyIn)
53     {
54         nTime = GetTime();
55         vchPubKey = vchPubKeyIn;
56     }
57
58     IMPLEMENT_SERIALIZE
59     (
60         if (!(nType & SER_GETHASH))
61             READWRITE(nVersion);
62         READWRITE(nTime);
63         READWRITE(vchPubKey);
64     )
65 };
66
67 /** Address book data */
68 class CAddressBookData
69 {
70 public:
71     std::string name;
72     std::string purpose;
73
74     CAddressBookData()
75     {
76         purpose = "unknown";
77     }
78 };
79
80 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
81  * and provides the ability to create new transactions.
82  */
83 class CWallet : public CCryptoKeyStore
84 {
85 private:
86     bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
87
88     CWalletDB *pwalletdbEncryption;
89
90     // the current wallet version: clients below this version are not able to load the wallet
91     int nWalletVersion;
92
93     // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
94     int nWalletMaxVersion;
95
96     int64 nNextResend;
97     int64 nLastResend;
98
99 public:
100     mutable CCriticalSection cs_wallet;
101
102     bool fFileBacked;
103     std::string strWalletFile;
104
105     std::set<int64> setKeyPool;
106     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
107
108     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
109     MasterKeyMap mapMasterKeys;
110     unsigned int nMasterKeyMaxID;
111
112     CWallet()
113     {
114         nWalletVersion = FEATURE_BASE;
115         nWalletMaxVersion = FEATURE_BASE;
116         fFileBacked = false;
117         nMasterKeyMaxID = 0;
118         pwalletdbEncryption = NULL;
119         nOrderPosNext = 0;
120         nNextResend = 0;
121         nLastResend = 0;
122     }
123     CWallet(std::string strWalletFileIn)
124     {
125         nWalletVersion = FEATURE_BASE;
126         nWalletMaxVersion = FEATURE_BASE;
127         strWalletFile = strWalletFileIn;
128         fFileBacked = true;
129         nMasterKeyMaxID = 0;
130         pwalletdbEncryption = NULL;
131         nOrderPosNext = 0;
132         nNextResend = 0;
133         nLastResend = 0;
134     }
135
136     std::map<uint256, CWalletTx> mapWallet;
137     int64 nOrderPosNext;
138     std::map<uint256, int> mapRequestCount;
139
140     std::map<CTxDestination, CAddressBookData> mapAddressBook;
141
142     CPubKey vchDefaultKey;
143
144     std::set<COutPoint> setLockedCoins;
145
146     int64 nTimeFirstKey;
147
148     // check whether we are allowed to upgrade (or already support) to the named feature
149     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
150
151     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
152     bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
153     bool IsLockedCoin(uint256 hash, unsigned int n) const;
154     void LockCoin(COutPoint& output);
155     void UnlockCoin(COutPoint& output);
156     void UnlockAllCoins();
157     void ListLockedCoins(std::vector<COutPoint>& vOutpts);
158
159     // keystore implementation
160     // Generate a new key
161     CPubKey GenerateNewKey();
162     // Adds a key to the store, and saves it to disk.
163     bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
164     // Adds a key to the store, without saving it to disk (used by LoadWallet)
165     bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
166     // Load metadata (used by LoadWallet)
167     bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
168
169     bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
170
171     // Adds an encrypted key to the store, and saves it to disk.
172     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
173     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
174     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
175     bool AddCScript(const CScript& redeemScript);
176     bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
177
178     bool Unlock(const SecureString& strWalletPassphrase);
179     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
180     bool EncryptWallet(const SecureString& strWalletPassphrase);
181
182     void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
183
184     /** Increment the next transaction order id
185         @return next transaction order id
186      */
187     int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
188
189     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
190     typedef std::multimap<int64, TxPair > TxItems;
191
192     /** Get the wallet's activity log
193         @return multimap of ordered transactions and accounting entries
194         @warning Returned pointers are *only* valid within the scope of passed acentries
195      */
196     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
197
198     void MarkDirty();
199     bool AddToWallet(const CWalletTx& wtxIn);
200     bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
201     bool EraseFromWallet(uint256 hash);
202     void WalletUpdateSpent(const CTransaction& prevout);
203     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
204     void ReacceptWalletTransactions();
205     void ResendWalletTransactions();
206     int64 GetBalance() const;
207     int64 GetUnconfirmedBalance() const;
208     int64 GetImmatureBalance() const;
209     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend,
210                            CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
211     bool CreateTransaction(CScript scriptPubKey, int64 nValue,
212                            CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
213     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
214     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
215     std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
216
217     bool NewKeyPool();
218     bool TopUpKeyPool(unsigned int kpSize = 0);
219     int64 AddReserveKey(const CKeyPool& keypool);
220     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
221     void KeepKey(int64 nIndex);
222     void ReturnKey(int64 nIndex);
223     bool GetKeyFromPool(CPubKey &key);
224     int64 GetOldestKeyPoolTime();
225     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
226
227     std::set< std::set<CTxDestination> > GetAddressGroupings();
228     std::map<CTxDestination, int64> GetAddressBalances();
229
230     std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
231
232     bool IsMine(const CTxIn& txin) const;
233     int64 GetDebit(const CTxIn& txin) const;
234     bool IsMine(const CTxOut& txout) const
235     {
236         return ::IsMine(*this, txout.scriptPubKey);
237     }
238     int64 GetCredit(const CTxOut& txout) const
239     {
240         if (!MoneyRange(txout.nValue))
241             throw std::runtime_error("CWallet::GetCredit() : value out of range");
242         return (IsMine(txout) ? txout.nValue : 0);
243     }
244     bool IsChange(const CTxOut& txout) const;
245     int64 GetChange(const CTxOut& txout) const
246     {
247         if (!MoneyRange(txout.nValue))
248             throw std::runtime_error("CWallet::GetChange() : value out of range");
249         return (IsChange(txout) ? txout.nValue : 0);
250     }
251     bool IsMine(const CTransaction& tx) const
252     {
253         BOOST_FOREACH(const CTxOut& txout, tx.vout)
254             if (IsMine(txout))
255                 return true;
256         return false;
257     }
258     bool IsFromMe(const CTransaction& tx) const
259     {
260         return (GetDebit(tx) > 0);
261     }
262     int64 GetDebit(const CTransaction& tx) const
263     {
264         int64 nDebit = 0;
265         BOOST_FOREACH(const CTxIn& txin, tx.vin)
266         {
267             nDebit += GetDebit(txin);
268             if (!MoneyRange(nDebit))
269                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
270         }
271         return nDebit;
272     }
273     int64 GetCredit(const CTransaction& tx) const
274     {
275         int64 nCredit = 0;
276         BOOST_FOREACH(const CTxOut& txout, tx.vout)
277         {
278             nCredit += GetCredit(txout);
279             if (!MoneyRange(nCredit))
280                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
281         }
282         return nCredit;
283     }
284     int64 GetChange(const CTransaction& tx) const
285     {
286         int64 nChange = 0;
287         BOOST_FOREACH(const CTxOut& txout, tx.vout)
288         {
289             nChange += GetChange(txout);
290             if (!MoneyRange(nChange))
291                 throw std::runtime_error("CWallet::GetChange() : value out of range");
292         }
293         return nChange;
294     }
295     void SetBestChain(const CBlockLocator& loc);
296
297     DBErrors LoadWallet(bool& fFirstRunRet);
298
299     bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
300
301     bool DelAddressBook(const CTxDestination& address);
302
303     void UpdatedTransaction(const uint256 &hashTx);
304
305     void PrintWallet(const CBlock& block);
306
307     void Inventory(const uint256 &hash)
308     {
309         {
310             LOCK(cs_wallet);
311             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
312             if (mi != mapRequestCount.end())
313                 (*mi).second++;
314         }
315     }
316
317     unsigned int GetKeyPoolSize()
318     {
319         return setKeyPool.size();
320     }
321
322     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
323
324     bool SetDefaultKey(const CPubKey &vchPubKey);
325
326     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
327     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
328
329     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
330     bool SetMaxVersion(int nVersion);
331
332     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
333     int GetVersion() { return nWalletVersion; }
334
335     /** Address book entry changed.
336      * @note called with lock cs_wallet held.
337      */
338     boost::signals2::signal<void (CWallet *wallet, const CTxDestination
339             &address, const std::string &label, bool isMine,
340             const std::string &purpose,
341             ChangeType status)> NotifyAddressBookChanged;
342
343     /** Wallet transaction added, removed or updated.
344      * @note called with lock cs_wallet held.
345      */
346     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
347             ChangeType status)> NotifyTransactionChanged;
348 };
349
350 /** A key allocated from the key pool. */
351 class CReserveKey
352 {
353 protected:
354     CWallet* pwallet;
355     int64 nIndex;
356     CPubKey vchPubKey;
357 public:
358     CReserveKey(CWallet* pwalletIn)
359     {
360         nIndex = -1;
361         pwallet = pwalletIn;
362     }
363
364     ~CReserveKey()
365     {
366         ReturnKey();
367     }
368
369     void ReturnKey();
370     bool GetReservedKey(CPubKey &pubkey);
371     void KeepKey();
372 };
373
374
375 typedef std::map<std::string, std::string> mapValue_t;
376
377
378 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
379 {
380     if (!mapValue.count("n"))
381     {
382         nOrderPos = -1; // TODO: calculate elsewhere
383         return;
384     }
385     nOrderPos = atoi64(mapValue["n"].c_str());
386 }
387
388
389 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
390 {
391     if (nOrderPos == -1)
392         return;
393     mapValue["n"] = i64tostr(nOrderPos);
394 }
395
396
397 /** A transaction with a bunch of additional info that only the owner cares about.
398  * It includes any unrecorded transactions needed to link it back to the block chain.
399  */
400 class CWalletTx : public CMerkleTx
401 {
402 private:
403     const CWallet* pwallet;
404
405 public:
406     std::vector<CMerkleTx> vtxPrev;
407     mapValue_t mapValue;
408     std::vector<std::pair<std::string, std::string> > vOrderForm;
409     unsigned int fTimeReceivedIsTxTime;
410     unsigned int nTimeReceived;  // time received by this node
411     unsigned int nTimeSmart;
412     char fFromMe;
413     std::string strFromAccount;
414     std::vector<char> vfSpent; // which outputs are already spent
415     int64 nOrderPos;  // position in ordered transaction list
416
417     // memory only
418     mutable bool fDebitCached;
419     mutable bool fCreditCached;
420     mutable bool fImmatureCreditCached;
421     mutable bool fAvailableCreditCached;
422     mutable bool fChangeCached;
423     mutable int64 nDebitCached;
424     mutable int64 nCreditCached;
425     mutable int64 nImmatureCreditCached;
426     mutable int64 nAvailableCreditCached;
427     mutable int64 nChangeCached;
428
429     CWalletTx()
430     {
431         Init(NULL);
432     }
433
434     CWalletTx(const CWallet* pwalletIn)
435     {
436         Init(pwalletIn);
437     }
438
439     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
440     {
441         Init(pwalletIn);
442     }
443
444     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
445     {
446         Init(pwalletIn);
447     }
448
449     void Init(const CWallet* pwalletIn)
450     {
451         pwallet = pwalletIn;
452         vtxPrev.clear();
453         mapValue.clear();
454         vOrderForm.clear();
455         fTimeReceivedIsTxTime = false;
456         nTimeReceived = 0;
457         nTimeSmart = 0;
458         fFromMe = false;
459         strFromAccount.clear();
460         vfSpent.clear();
461         fDebitCached = false;
462         fCreditCached = false;
463         fImmatureCreditCached = false;
464         fAvailableCreditCached = false;
465         fChangeCached = false;
466         nDebitCached = 0;
467         nCreditCached = 0;
468         nImmatureCreditCached = 0;
469         nAvailableCreditCached = 0;
470         nChangeCached = 0;
471         nOrderPos = -1;
472     }
473
474     IMPLEMENT_SERIALIZE
475     (
476         CWalletTx* pthis = const_cast<CWalletTx*>(this);
477         if (fRead)
478             pthis->Init(NULL);
479         char fSpent = false;
480
481         if (!fRead)
482         {
483             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
484
485             std::string str;
486             BOOST_FOREACH(char f, vfSpent)
487             {
488                 str += (f ? '1' : '0');
489                 if (f)
490                     fSpent = true;
491             }
492             pthis->mapValue["spent"] = str;
493
494             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
495
496             if (nTimeSmart)
497                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
498         }
499
500         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
501         READWRITE(vtxPrev);
502         READWRITE(mapValue);
503         READWRITE(vOrderForm);
504         READWRITE(fTimeReceivedIsTxTime);
505         READWRITE(nTimeReceived);
506         READWRITE(fFromMe);
507         READWRITE(fSpent);
508
509         if (fRead)
510         {
511             pthis->strFromAccount = pthis->mapValue["fromaccount"];
512
513             if (mapValue.count("spent"))
514                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
515                     pthis->vfSpent.push_back(c != '0');
516             else
517                 pthis->vfSpent.assign(vout.size(), fSpent);
518
519             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
520
521             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
522         }
523
524         pthis->mapValue.erase("fromaccount");
525         pthis->mapValue.erase("version");
526         pthis->mapValue.erase("spent");
527         pthis->mapValue.erase("n");
528         pthis->mapValue.erase("timesmart");
529     )
530
531     // marks certain txout's as spent
532     // returns true if any update took place
533     bool UpdateSpent(const std::vector<char>& vfNewSpent)
534     {
535         bool fReturn = false;
536         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
537         {
538             if (i == vfSpent.size())
539                 break;
540
541             if (vfNewSpent[i] && !vfSpent[i])
542             {
543                 vfSpent[i] = true;
544                 fReturn = true;
545                 fAvailableCreditCached = false;
546             }
547         }
548         return fReturn;
549     }
550
551     // make sure balances are recalculated
552     void MarkDirty()
553     {
554         fCreditCached = false;
555         fAvailableCreditCached = false;
556         fDebitCached = false;
557         fChangeCached = false;
558     }
559
560     void BindWallet(CWallet *pwalletIn)
561     {
562         pwallet = pwalletIn;
563         MarkDirty();
564     }
565
566     void MarkSpent(unsigned int nOut)
567     {
568         if (nOut >= vout.size())
569             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
570         vfSpent.resize(vout.size());
571         if (!vfSpent[nOut])
572         {
573             vfSpent[nOut] = true;
574             fAvailableCreditCached = false;
575         }
576     }
577
578     bool IsSpent(unsigned int nOut) const
579     {
580         if (nOut >= vout.size())
581             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
582         if (nOut >= vfSpent.size())
583             return false;
584         return (!!vfSpent[nOut]);
585     }
586
587     int64 GetDebit() const
588     {
589         if (vin.empty())
590             return 0;
591         if (fDebitCached)
592             return nDebitCached;
593         nDebitCached = pwallet->GetDebit(*this);
594         fDebitCached = true;
595         return nDebitCached;
596     }
597
598     int64 GetCredit(bool fUseCache=true) const
599     {
600         // Must wait until coinbase is safely deep enough in the chain before valuing it
601         if (IsCoinBase() && GetBlocksToMaturity() > 0)
602             return 0;
603
604         // GetBalance can assume transactions in mapWallet won't change
605         if (fUseCache && fCreditCached)
606             return nCreditCached;
607         nCreditCached = pwallet->GetCredit(*this);
608         fCreditCached = true;
609         return nCreditCached;
610     }
611
612     int64 GetImmatureCredit(bool fUseCache=true) const
613     {
614         if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
615         {
616             if (fUseCache && fImmatureCreditCached)
617                 return nImmatureCreditCached;
618             nImmatureCreditCached = pwallet->GetCredit(*this);
619             fImmatureCreditCached = true;
620             return nImmatureCreditCached;
621         }
622
623         return 0;
624     }
625
626     int64 GetAvailableCredit(bool fUseCache=true) const
627     {
628         // Must wait until coinbase is safely deep enough in the chain before valuing it
629         if (IsCoinBase() && GetBlocksToMaturity() > 0)
630             return 0;
631
632         if (fUseCache && fAvailableCreditCached)
633             return nAvailableCreditCached;
634
635         int64 nCredit = 0;
636         for (unsigned int i = 0; i < vout.size(); i++)
637         {
638             if (!IsSpent(i))
639             {
640                 const CTxOut &txout = vout[i];
641                 nCredit += pwallet->GetCredit(txout);
642                 if (!MoneyRange(nCredit))
643                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
644             }
645         }
646
647         nAvailableCreditCached = nCredit;
648         fAvailableCreditCached = true;
649         return nCredit;
650     }
651
652
653     int64 GetChange() const
654     {
655         if (fChangeCached)
656             return nChangeCached;
657         nChangeCached = pwallet->GetChange(*this);
658         fChangeCached = true;
659         return nChangeCached;
660     }
661
662     void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
663                     std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
664
665     void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
666                            int64& nSent, int64& nFee) const;
667
668     bool IsFromMe() const
669     {
670         return (GetDebit() > 0);
671     }
672
673     bool IsConfirmed() const
674     {
675         // Quick answer in most cases
676         if (!IsFinalTx(*this))
677             return false;
678         if (GetDepthInMainChain() >= 1)
679             return true;
680         if (!IsFromMe()) // using wtx's cached debit
681             return false;
682
683         // If no confirmations but it's from us, we can still
684         // consider it confirmed if all dependencies are confirmed
685         std::map<uint256, const CMerkleTx*> mapPrev;
686         std::vector<const CMerkleTx*> vWorkQueue;
687         vWorkQueue.reserve(vtxPrev.size()+1);
688         vWorkQueue.push_back(this);
689         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
690         {
691             const CMerkleTx* ptx = vWorkQueue[i];
692
693             if (!IsFinalTx(*ptx))
694                 return false;
695             if (ptx->GetDepthInMainChain() >= 1)
696                 continue;
697             if (!pwallet->IsFromMe(*ptx))
698                 return false;
699
700             if (mapPrev.empty())
701             {
702                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
703                     mapPrev[tx.GetHash()] = &tx;
704             }
705
706             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
707             {
708                 if (!mapPrev.count(txin.prevout.hash))
709                     return false;
710                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
711             }
712         }
713         return true;
714     }
715
716     bool WriteToDisk();
717
718     int64 GetTxTime() const;
719     int GetRequestCount() const;
720
721     void AddSupportingTransactions();
722     bool AcceptWalletTransaction();
723     void RelayWalletTransaction();
724 };
725
726
727
728
729 class COutput
730 {
731 public:
732     const CWalletTx *tx;
733     int i;
734     int nDepth;
735
736     COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
737     {
738         tx = txIn; i = iIn; nDepth = nDepthIn;
739     }
740
741     std::string ToString() const
742     {
743         return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
744     }
745
746     void print() const
747     {
748         printf("%s\n", ToString().c_str());
749     }
750 };
751
752
753
754
755 /** Private key that includes an expiration date in case it never gets used. */
756 class CWalletKey
757 {
758 public:
759     CPrivKey vchPrivKey;
760     int64 nTimeCreated;
761     int64 nTimeExpires;
762     std::string strComment;
763     //// todo: add something to note what created it (user, getnewaddress, change)
764     ////   maybe should have a map<string, string> property map
765
766     CWalletKey(int64 nExpires=0)
767     {
768         nTimeCreated = (nExpires ? GetTime() : 0);
769         nTimeExpires = nExpires;
770     }
771
772     IMPLEMENT_SERIALIZE
773     (
774         if (!(nType & SER_GETHASH))
775             READWRITE(nVersion);
776         READWRITE(vchPrivKey);
777         READWRITE(nTimeCreated);
778         READWRITE(nTimeExpires);
779         READWRITE(strComment);
780     )
781 };
782
783
784
785
786
787
788 /** Account information.
789  * Stored in wallet with key "acc"+string account name.
790  */
791 class CAccount
792 {
793 public:
794     CPubKey vchPubKey;
795
796     CAccount()
797     {
798         SetNull();
799     }
800
801     void SetNull()
802     {
803         vchPubKey = CPubKey();
804     }
805
806     IMPLEMENT_SERIALIZE
807     (
808         if (!(nType & SER_GETHASH))
809             READWRITE(nVersion);
810         READWRITE(vchPubKey);
811     )
812 };
813
814
815
816 /** Internal transfers.
817  * Database key is acentry<account><counter>.
818  */
819 class CAccountingEntry
820 {
821 public:
822     std::string strAccount;
823     int64 nCreditDebit;
824     int64 nTime;
825     std::string strOtherAccount;
826     std::string strComment;
827     mapValue_t mapValue;
828     int64 nOrderPos;  // position in ordered transaction list
829     uint64 nEntryNo;
830
831     CAccountingEntry()
832     {
833         SetNull();
834     }
835
836     void SetNull()
837     {
838         nCreditDebit = 0;
839         nTime = 0;
840         strAccount.clear();
841         strOtherAccount.clear();
842         strComment.clear();
843         nOrderPos = -1;
844     }
845
846     IMPLEMENT_SERIALIZE
847     (
848         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
849         if (!(nType & SER_GETHASH))
850             READWRITE(nVersion);
851         // Note: strAccount is serialized as part of the key, not here.
852         READWRITE(nCreditDebit);
853         READWRITE(nTime);
854         READWRITE(strOtherAccount);
855
856         if (!fRead)
857         {
858             WriteOrderPos(nOrderPos, me.mapValue);
859
860             if (!(mapValue.empty() && _ssExtra.empty()))
861             {
862                 CDataStream ss(nType, nVersion);
863                 ss.insert(ss.begin(), '\0');
864                 ss << mapValue;
865                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
866                 me.strComment.append(ss.str());
867             }
868         }
869
870         READWRITE(strComment);
871
872         size_t nSepPos = strComment.find("\0", 0, 1);
873         if (fRead)
874         {
875             me.mapValue.clear();
876             if (std::string::npos != nSepPos)
877             {
878                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
879                 ss >> me.mapValue;
880                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
881             }
882             ReadOrderPos(me.nOrderPos, me.mapValue);
883         }
884         if (std::string::npos != nSepPos)
885             me.strComment.erase(nSepPos);
886
887         me.mapValue.erase("n");
888     )
889
890 private:
891     std::vector<char> _ssExtra;
892 };
893
894 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
895
896 #endif
This page took 0.07048 seconds and 4 git commands to generate.