Refactor SelectCoinsMinConf() and add unit tests.
[bitcoinplatinum.git] / src / wallet.h
blobb2e0e5260eb142cb4c4ac3a66690b9afa589afd3
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
8 #include "main.h"
9 #include "key.h"
10 #include "keystore.h"
11 #include "script.h"
12 #include "ui_interface.h"
14 class CWalletTx;
15 class CReserveKey;
16 class CWalletDB;
17 class COutput;
19 /** (client) version numbers for particular wallet features */
20 enum WalletFeature
22 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
24 FEATURE_WALLETCRYPT = 40000, // wallet encryption
25 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
27 FEATURE_LATEST = 60000
31 /** A key pool entry */
32 class CKeyPool
34 public:
35 int64 nTime;
36 CPubKey vchPubKey;
38 CKeyPool()
40 nTime = GetTime();
43 CKeyPool(const CPubKey& vchPubKeyIn)
45 nTime = GetTime();
46 vchPubKey = vchPubKeyIn;
49 IMPLEMENT_SERIALIZE
51 if (!(nType & SER_GETHASH))
52 READWRITE(nVersion);
53 READWRITE(nTime);
54 READWRITE(vchPubKey);
58 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
59 * and provides the ability to create new transactions.
61 class CWallet : public CCryptoKeyStore
63 private:
64 void AvailableCoins(std::vector<COutput>& vCoins) const;
65 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
67 CWalletDB *pwalletdbEncryption;
69 // the current wallet version: clients below this version are not able to load the wallet
70 int nWalletVersion;
72 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
73 int nWalletMaxVersion;
75 public:
76 mutable CCriticalSection cs_wallet;
78 bool fFileBacked;
79 std::string strWalletFile;
81 std::set<int64> setKeyPool;
84 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
85 MasterKeyMap mapMasterKeys;
86 unsigned int nMasterKeyMaxID;
88 CWallet()
90 nWalletVersion = FEATURE_BASE;
91 nWalletMaxVersion = FEATURE_BASE;
92 fFileBacked = false;
93 nMasterKeyMaxID = 0;
94 pwalletdbEncryption = NULL;
96 CWallet(std::string strWalletFileIn)
98 nWalletVersion = FEATURE_BASE;
99 nWalletMaxVersion = FEATURE_BASE;
100 strWalletFile = strWalletFileIn;
101 fFileBacked = true;
102 nMasterKeyMaxID = 0;
103 pwalletdbEncryption = NULL;
106 std::map<uint256, CWalletTx> mapWallet;
107 std::map<uint256, int> mapRequestCount;
109 std::map<CTxDestination, std::string> mapAddressBook;
111 CPubKey vchDefaultKey;
113 // check whether we are allowed to upgrade (or already support) to the named feature
114 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
116 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
118 // keystore implementation
119 // Generate a new key
120 CPubKey GenerateNewKey();
121 // Adds a key to the store, and saves it to disk.
122 bool AddKey(const CKey& key);
123 // Adds a key to the store, without saving it to disk (used by LoadWallet)
124 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
126 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
128 // Adds an encrypted key to the store, and saves it to disk.
129 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
130 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
131 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
132 bool AddCScript(const CScript& redeemScript);
133 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
135 bool Unlock(const SecureString& strWalletPassphrase);
136 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
137 bool EncryptWallet(const SecureString& strWalletPassphrase);
139 void MarkDirty();
140 bool AddToWallet(const CWalletTx& wtxIn);
141 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
142 bool EraseFromWallet(uint256 hash);
143 void WalletUpdateSpent(const CTransaction& prevout);
144 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
145 int ScanForWalletTransaction(const uint256& hashTx);
146 void ReacceptWalletTransactions();
147 void ResendWalletTransactions();
148 int64 GetBalance() const;
149 int64 GetUnconfirmedBalance() const;
150 int64 GetImmatureBalance() const;
151 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
152 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
153 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
154 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
155 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
157 bool NewKeyPool();
158 bool TopUpKeyPool();
159 int64 AddReserveKey(const CKeyPool& keypool);
160 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
161 void KeepKey(int64 nIndex);
162 void ReturnKey(int64 nIndex);
163 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
164 int64 GetOldestKeyPoolTime();
165 void GetAllReserveKeys(std::set<CKeyID>& setAddress);
167 bool IsMine(const CTxIn& txin) const;
168 int64 GetDebit(const CTxIn& txin) const;
169 bool IsMine(const CTxOut& txout) const
171 return ::IsMine(*this, txout.scriptPubKey);
173 int64 GetCredit(const CTxOut& txout) const
175 if (!MoneyRange(txout.nValue))
176 throw std::runtime_error("CWallet::GetCredit() : value out of range");
177 return (IsMine(txout) ? txout.nValue : 0);
179 bool IsChange(const CTxOut& txout) const;
180 int64 GetChange(const CTxOut& txout) const
182 if (!MoneyRange(txout.nValue))
183 throw std::runtime_error("CWallet::GetChange() : value out of range");
184 return (IsChange(txout) ? txout.nValue : 0);
186 bool IsMine(const CTransaction& tx) const
188 BOOST_FOREACH(const CTxOut& txout, tx.vout)
189 if (IsMine(txout))
190 return true;
191 return false;
193 bool IsFromMe(const CTransaction& tx) const
195 return (GetDebit(tx) > 0);
197 int64 GetDebit(const CTransaction& tx) const
199 int64 nDebit = 0;
200 BOOST_FOREACH(const CTxIn& txin, tx.vin)
202 nDebit += GetDebit(txin);
203 if (!MoneyRange(nDebit))
204 throw std::runtime_error("CWallet::GetDebit() : value out of range");
206 return nDebit;
208 int64 GetCredit(const CTransaction& tx) const
210 int64 nCredit = 0;
211 BOOST_FOREACH(const CTxOut& txout, tx.vout)
213 nCredit += GetCredit(txout);
214 if (!MoneyRange(nCredit))
215 throw std::runtime_error("CWallet::GetCredit() : value out of range");
217 return nCredit;
219 int64 GetChange(const CTransaction& tx) const
221 int64 nChange = 0;
222 BOOST_FOREACH(const CTxOut& txout, tx.vout)
224 nChange += GetChange(txout);
225 if (!MoneyRange(nChange))
226 throw std::runtime_error("CWallet::GetChange() : value out of range");
228 return nChange;
230 void SetBestChain(const CBlockLocator& loc);
232 int LoadWallet(bool& fFirstRunRet);
234 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
236 bool DelAddressBookName(const CTxDestination& address);
238 void UpdatedTransaction(const uint256 &hashTx);
240 void PrintWallet(const CBlock& block);
242 void Inventory(const uint256 &hash)
245 LOCK(cs_wallet);
246 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
247 if (mi != mapRequestCount.end())
248 (*mi).second++;
252 int GetKeyPoolSize()
254 return setKeyPool.size();
257 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
259 bool SetDefaultKey(const CPubKey &vchPubKey);
261 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
262 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
264 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
265 bool SetMaxVersion(int nVersion);
267 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
268 int GetVersion() { return nWalletVersion; }
270 /** Address book entry changed.
271 * @note called with lock cs_wallet held.
273 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
275 /** Wallet transaction added, removed or updated.
276 * @note called with lock cs_wallet held.
278 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
281 /** A key allocated from the key pool. */
282 class CReserveKey
284 protected:
285 CWallet* pwallet;
286 int64 nIndex;
287 CPubKey vchPubKey;
288 public:
289 CReserveKey(CWallet* pwalletIn)
291 nIndex = -1;
292 pwallet = pwalletIn;
295 ~CReserveKey()
297 if (!fShutdown)
298 ReturnKey();
301 void ReturnKey();
302 CPubKey GetReservedKey();
303 void KeepKey();
307 /** A transaction with a bunch of additional info that only the owner cares about.
308 * It includes any unrecorded transactions needed to link it back to the block chain.
310 class CWalletTx : public CMerkleTx
312 private:
313 const CWallet* pwallet;
315 public:
316 std::vector<CMerkleTx> vtxPrev;
317 std::map<std::string, std::string> mapValue;
318 std::vector<std::pair<std::string, std::string> > vOrderForm;
319 unsigned int fTimeReceivedIsTxTime;
320 unsigned int nTimeReceived; // time received by this node
321 char fFromMe;
322 std::string strFromAccount;
323 std::vector<char> vfSpent; // which outputs are already spent
325 // memory only
326 mutable bool fDebitCached;
327 mutable bool fCreditCached;
328 mutable bool fAvailableCreditCached;
329 mutable bool fChangeCached;
330 mutable int64 nDebitCached;
331 mutable int64 nCreditCached;
332 mutable int64 nAvailableCreditCached;
333 mutable int64 nChangeCached;
335 CWalletTx()
337 Init(NULL);
340 CWalletTx(const CWallet* pwalletIn)
342 Init(pwalletIn);
345 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
347 Init(pwalletIn);
350 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
352 Init(pwalletIn);
355 void Init(const CWallet* pwalletIn)
357 pwallet = pwalletIn;
358 vtxPrev.clear();
359 mapValue.clear();
360 vOrderForm.clear();
361 fTimeReceivedIsTxTime = false;
362 nTimeReceived = 0;
363 fFromMe = false;
364 strFromAccount.clear();
365 vfSpent.clear();
366 fDebitCached = false;
367 fCreditCached = false;
368 fAvailableCreditCached = false;
369 fChangeCached = false;
370 nDebitCached = 0;
371 nCreditCached = 0;
372 nAvailableCreditCached = 0;
373 nChangeCached = 0;
376 IMPLEMENT_SERIALIZE
378 CWalletTx* pthis = const_cast<CWalletTx*>(this);
379 if (fRead)
380 pthis->Init(NULL);
381 char fSpent = false;
383 if (!fRead)
385 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
387 std::string str;
388 BOOST_FOREACH(char f, vfSpent)
390 str += (f ? '1' : '0');
391 if (f)
392 fSpent = true;
394 pthis->mapValue["spent"] = str;
397 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
398 READWRITE(vtxPrev);
399 READWRITE(mapValue);
400 READWRITE(vOrderForm);
401 READWRITE(fTimeReceivedIsTxTime);
402 READWRITE(nTimeReceived);
403 READWRITE(fFromMe);
404 READWRITE(fSpent);
406 if (fRead)
408 pthis->strFromAccount = pthis->mapValue["fromaccount"];
410 if (mapValue.count("spent"))
411 BOOST_FOREACH(char c, pthis->mapValue["spent"])
412 pthis->vfSpent.push_back(c != '0');
413 else
414 pthis->vfSpent.assign(vout.size(), fSpent);
417 pthis->mapValue.erase("fromaccount");
418 pthis->mapValue.erase("version");
419 pthis->mapValue.erase("spent");
422 // marks certain txout's as spent
423 // returns true if any update took place
424 bool UpdateSpent(const std::vector<char>& vfNewSpent)
426 bool fReturn = false;
427 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
429 if (i == vfSpent.size())
430 break;
432 if (vfNewSpent[i] && !vfSpent[i])
434 vfSpent[i] = true;
435 fReturn = true;
436 fAvailableCreditCached = false;
439 return fReturn;
442 // make sure balances are recalculated
443 void MarkDirty()
445 fCreditCached = false;
446 fAvailableCreditCached = false;
447 fDebitCached = false;
448 fChangeCached = false;
451 void BindWallet(CWallet *pwalletIn)
453 pwallet = pwalletIn;
454 MarkDirty();
457 void MarkSpent(unsigned int nOut)
459 if (nOut >= vout.size())
460 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
461 vfSpent.resize(vout.size());
462 if (!vfSpent[nOut])
464 vfSpent[nOut] = true;
465 fAvailableCreditCached = false;
469 bool IsSpent(unsigned int nOut) const
471 if (nOut >= vout.size())
472 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
473 if (nOut >= vfSpent.size())
474 return false;
475 return (!!vfSpent[nOut]);
478 int64 GetDebit() const
480 if (vin.empty())
481 return 0;
482 if (fDebitCached)
483 return nDebitCached;
484 nDebitCached = pwallet->GetDebit(*this);
485 fDebitCached = true;
486 return nDebitCached;
489 int64 GetCredit(bool fUseCache=true) const
491 // Must wait until coinbase is safely deep enough in the chain before valuing it
492 if (IsCoinBase() && GetBlocksToMaturity() > 0)
493 return 0;
495 // GetBalance can assume transactions in mapWallet won't change
496 if (fUseCache && fCreditCached)
497 return nCreditCached;
498 nCreditCached = pwallet->GetCredit(*this);
499 fCreditCached = true;
500 return nCreditCached;
503 int64 GetAvailableCredit(bool fUseCache=true) const
505 // Must wait until coinbase is safely deep enough in the chain before valuing it
506 if (IsCoinBase() && GetBlocksToMaturity() > 0)
507 return 0;
509 if (fUseCache && fAvailableCreditCached)
510 return nAvailableCreditCached;
512 int64 nCredit = 0;
513 for (unsigned int i = 0; i < vout.size(); i++)
515 if (!IsSpent(i))
517 const CTxOut &txout = vout[i];
518 nCredit += pwallet->GetCredit(txout);
519 if (!MoneyRange(nCredit))
520 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
524 nAvailableCreditCached = nCredit;
525 fAvailableCreditCached = true;
526 return nCredit;
530 int64 GetChange() const
532 if (fChangeCached)
533 return nChangeCached;
534 nChangeCached = pwallet->GetChange(*this);
535 fChangeCached = true;
536 return nChangeCached;
539 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
540 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
542 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
543 int64& nSent, int64& nFee) const;
545 bool IsFromMe() const
547 return (GetDebit() > 0);
550 bool IsConfirmed() const
552 // Quick answer in most cases
553 if (!IsFinal())
554 return false;
555 if (GetDepthInMainChain() >= 1)
556 return true;
557 if (!IsFromMe()) // using wtx's cached debit
558 return false;
560 // If no confirmations but it's from us, we can still
561 // consider it confirmed if all dependencies are confirmed
562 std::map<uint256, const CMerkleTx*> mapPrev;
563 std::vector<const CMerkleTx*> vWorkQueue;
564 vWorkQueue.reserve(vtxPrev.size()+1);
565 vWorkQueue.push_back(this);
566 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
568 const CMerkleTx* ptx = vWorkQueue[i];
570 if (!ptx->IsFinal())
571 return false;
572 if (ptx->GetDepthInMainChain() >= 1)
573 continue;
574 if (!pwallet->IsFromMe(*ptx))
575 return false;
577 if (mapPrev.empty())
579 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
580 mapPrev[tx.GetHash()] = &tx;
583 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
585 if (!mapPrev.count(txin.prevout.hash))
586 return false;
587 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
590 return true;
593 bool WriteToDisk();
595 int64 GetTxTime() const;
596 int GetRequestCount() const;
598 void AddSupportingTransactions(CTxDB& txdb);
600 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
601 bool AcceptWalletTransaction();
603 void RelayWalletTransaction(CTxDB& txdb);
604 void RelayWalletTransaction();
610 class COutput
612 public:
613 const CWalletTx *tx;
614 int i;
615 int nDepth;
617 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
619 tx = txIn; i = iIn; nDepth = nDepthIn;
622 std::string ToString() const
624 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
627 void print() const
629 printf("%s\n", ToString().c_str());
636 /** Private key that includes an expiration date in case it never gets used. */
637 class CWalletKey
639 public:
640 CPrivKey vchPrivKey;
641 int64 nTimeCreated;
642 int64 nTimeExpires;
643 std::string strComment;
644 //// todo: add something to note what created it (user, getnewaddress, change)
645 //// maybe should have a map<string, string> property map
647 CWalletKey(int64 nExpires=0)
649 nTimeCreated = (nExpires ? GetTime() : 0);
650 nTimeExpires = nExpires;
653 IMPLEMENT_SERIALIZE
655 if (!(nType & SER_GETHASH))
656 READWRITE(nVersion);
657 READWRITE(vchPrivKey);
658 READWRITE(nTimeCreated);
659 READWRITE(nTimeExpires);
660 READWRITE(strComment);
669 /** Account information.
670 * Stored in wallet with key "acc"+string account name.
672 class CAccount
674 public:
675 CPubKey vchPubKey;
677 CAccount()
679 SetNull();
682 void SetNull()
684 vchPubKey = CPubKey();
687 IMPLEMENT_SERIALIZE
689 if (!(nType & SER_GETHASH))
690 READWRITE(nVersion);
691 READWRITE(vchPubKey);
697 /** Internal transfers.
698 * Database key is acentry<account><counter>.
700 class CAccountingEntry
702 public:
703 std::string strAccount;
704 int64 nCreditDebit;
705 int64 nTime;
706 std::string strOtherAccount;
707 std::string strComment;
709 CAccountingEntry()
711 SetNull();
714 void SetNull()
716 nCreditDebit = 0;
717 nTime = 0;
718 strAccount.clear();
719 strOtherAccount.clear();
720 strComment.clear();
723 IMPLEMENT_SERIALIZE
725 if (!(nType & SER_GETHASH))
726 READWRITE(nVersion);
727 // Note: strAccount is serialized as part of the key, not here.
728 READWRITE(nCreditDebit);
729 READWRITE(nTime);
730 READWRITE(strOtherAccount);
731 READWRITE(strComment);
735 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
737 #endif