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