-
+ EBCC63EDB754B725C3C30121754F4D0B6F315773EFA6B077C04539F93E08AB625D8473A8F3F3FE5A1BEA59301EC01D7F76FB97C070F96D9DF5BFB1A4605B1000
bitcoin/src/wallet.h
(0 . 0)(1 . 676)
28119 // /****************************\
28120 // * EXPERIMENTAL BRANCH. *
28121 // * FOR LABORATORY USE ONLY. *
28122 // ********************************
28123 // ************
28124 // **************
28125 // ****************
28126 // **** **** ****
28127 // *** *** ***
28128 // *** *** ***
28129 // *** * * **
28130 // ******** ********
28131 // ******* ******
28132 // *** **
28133 // * ******* **
28134 // ** * * * * *
28135 // ** * * ***
28136 // **** * * * * ****
28137 // **** *** * * ** ***
28138 // **** ********* ******
28139 // ******* ***** *******
28140 // ********* ****** **
28141 // ** ****** ******
28142 // ** ******* **
28143 // ** ******* ***
28144 // **** ******** ************
28145 // ************ ************
28146 // ******** *******
28147 // ****** ****
28148 // *** ***
28149 // ********************************
28150 // Copyright (c) 2009-2010 Satoshi Nakamoto
28151 // Copyright (c) 2009-2012 The Bitcoin developers
28152 // Distributed under the MIT/X11 software license, see the accompanying
28153 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
28154 #ifndef BITCOIN_WALLET_H
28155 #define BITCOIN_WALLET_H
28156
28157 #include "bignum.h"
28158 #include "key.h"
28159 #include "script.h"
28160
28161 class CWalletTx;
28162 class CReserveKey;
28163 class CWalletDB;
28164
28165 // A CWallet is an extension of a keystore, which also maintains a set of
28166 // transactions and balances, and provides the ability to create new
28167 // transactions
28168 class CWallet : public CCryptoKeyStore
28169 {
28170 private:
28171 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
28172 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
28173
28174 CWalletDB *pwalletdbEncryption;
28175
28176 public:
28177 mutable CCriticalSection cs_wallet;
28178
28179 bool fFileBacked;
28180 std::string strWalletFile;
28181
28182 std::set<int64> setKeyPool;
28183
28184 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
28185 MasterKeyMap mapMasterKeys;
28186 unsigned int nMasterKeyMaxID;
28187
28188 CWallet()
28189 {
28190 fFileBacked = false;
28191 nMasterKeyMaxID = 0;
28192 pwalletdbEncryption = NULL;
28193 }
28194 CWallet(std::string strWalletFileIn)
28195 {
28196 strWalletFile = strWalletFileIn;
28197 fFileBacked = true;
28198 nMasterKeyMaxID = 0;
28199 pwalletdbEncryption = NULL;
28200 }
28201
28202 std::map<uint256, CWalletTx> mapWallet;
28203 std::vector<uint256> vWalletUpdated;
28204
28205 std::map<uint256, int> mapRequestCount;
28206
28207 std::map<CBitcoinAddress, std::string> mapAddressBook;
28208
28209 std::vector<unsigned char> vchDefaultKey;
28210
28211 // keystore implementation
28212 // Adds a key to the store, and saves it to disk.
28213 bool AddKey(const CKey& key);
28214 // Adds a key to the store, without saving it to disk (used by LoadWallet)
28215 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
28216
28217 // Adds an encrypted key to the store, and saves it to disk.
28218 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
28219 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
28220 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
28221
28222 bool Unlock(const SecureString& strWalletPassphrase);
28223 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
28224 bool EncryptWallet(const SecureString& strWalletPassphrase);
28225
28226 bool AddToWallet(const CWalletTx& wtxIn);
28227 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
28228 bool EraseFromWallet(uint256 hash);
28229 void WalletUpdateSpent(const CTransaction& prevout);
28230 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
28231 void ReacceptWalletTransactions();
28232 void ResendWalletTransactions();
28233 int64 GetBalance() const;
28234 int64 GetUnconfirmedBalance() const;
28235 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
28236 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
28237 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
28238 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
28239 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
28240
28241 bool NewKeyPool();
28242 bool TopUpKeyPool();
28243 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
28244 void KeepKey(int64 nIndex);
28245 void ReturnKey(int64 nIndex);
28246 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
28247 int64 GetOldestKeyPoolTime();
28248
28249 bool IsMine(const CTxIn& txin) const;
28250 int64 GetDebit(const CTxIn& txin) const;
28251 bool IsMine(const CTxOut& txout) const
28252 {
28253 return ::IsMine(*this, txout.scriptPubKey);
28254 }
28255 int64 GetCredit(const CTxOut& txout) const
28256 {
28257 if (!MoneyRange(txout.nValue))
28258 throw std::runtime_error("CWallet::GetCredit() : value out of range");
28259 return (IsMine(txout) ? txout.nValue : 0);
28260 }
28261 bool IsChange(const CTxOut& txout) const
28262 {
28263 CBitcoinAddress address;
28264 if (ExtractAddress(txout.scriptPubKey, this, address))
28265 CRITICAL_BLOCK(cs_wallet)
28266 if (!mapAddressBook.count(address))
28267 return true;
28268 return false;
28269 }
28270 int64 GetChange(const CTxOut& txout) const
28271 {
28272 if (!MoneyRange(txout.nValue))
28273 throw std::runtime_error("CWallet::GetChange() : value out of range");
28274 return (IsChange(txout) ? txout.nValue : 0);
28275 }
28276 bool IsMine(const CTransaction& tx) const
28277 {
28278 BOOST_FOREACH(const CTxOut& txout, tx.vout)
28279 if (IsMine(txout))
28280 return true;
28281 return false;
28282 }
28283 bool IsFromMe(const CTransaction& tx) const
28284 {
28285 return (GetDebit(tx) > 0);
28286 }
28287 int64 GetDebit(const CTransaction& tx) const
28288 {
28289 int64 nDebit = 0;
28290 BOOST_FOREACH(const CTxIn& txin, tx.vin)
28291 {
28292 nDebit += GetDebit(txin);
28293 if (!MoneyRange(nDebit))
28294 throw std::runtime_error("CWallet::GetDebit() : value out of range");
28295 }
28296 return nDebit;
28297 }
28298 int64 GetCredit(const CTransaction& tx) const
28299 {
28300 int64 nCredit = 0;
28301 BOOST_FOREACH(const CTxOut& txout, tx.vout)
28302 {
28303 nCredit += GetCredit(txout);
28304 if (!MoneyRange(nCredit))
28305 throw std::runtime_error("CWallet::GetCredit() : value out of range");
28306 }
28307 return nCredit;
28308 }
28309 int64 GetChange(const CTransaction& tx) const
28310 {
28311 int64 nChange = 0;
28312 BOOST_FOREACH(const CTxOut& txout, tx.vout)
28313 {
28314 nChange += GetChange(txout);
28315 if (!MoneyRange(nChange))
28316 throw std::runtime_error("CWallet::GetChange() : value out of range");
28317 }
28318 return nChange;
28319 }
28320 void SetBestChain(const CBlockLocator& loc)
28321 {
28322 CWalletDB walletdb(strWalletFile);
28323 walletdb.WriteBestBlock(loc);
28324 }
28325
28326 int LoadWallet(bool& fFirstRunRet);
28327 // bool BackupWallet(const std::string& strDest);
28328
28329 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
28330
28331 bool DelAddressBookName(const CBitcoinAddress& address);
28332
28333 void UpdatedTransaction(const uint256 &hashTx)
28334 {
28335 CRITICAL_BLOCK(cs_wallet)
28336 vWalletUpdated.push_back(hashTx);
28337 }
28338
28339 void PrintWallet(const CBlock& block);
28340
28341 void Inventory(const uint256 &hash)
28342 {
28343 CRITICAL_BLOCK(cs_wallet)
28344 {
28345 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
28346 if (mi != mapRequestCount.end())
28347 (*mi).second++;
28348 }
28349 }
28350
28351 int GetKeyPoolSize()
28352 {
28353 return setKeyPool.size();
28354 }
28355
28356 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
28357
28358 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
28359 };
28360
28361
28362 class CReserveKey
28363 {
28364 protected:
28365 CWallet* pwallet;
28366 int64 nIndex;
28367 std::vector<unsigned char> vchPubKey;
28368 public:
28369 CReserveKey(CWallet* pwalletIn)
28370 {
28371 nIndex = -1;
28372 pwallet = pwalletIn;
28373 }
28374
28375 ~CReserveKey()
28376 {
28377 if (!fShutdown)
28378 ReturnKey();
28379 }
28380
28381 void ReturnKey();
28382 std::vector<unsigned char> GetReservedKey();
28383 void KeepKey();
28384 };
28385
28386
28387 //
28388 // A transaction with a bunch of additional info that only the owner cares
28389 // about. It includes any unrecorded transactions needed to link it back
28390 // to the block chain.
28391 //
28392 class CWalletTx : public CMerkleTx
28393 {
28394 public:
28395 const CWallet* pwallet;
28396
28397 std::vector<CMerkleTx> vtxPrev;
28398 std::map<std::string, std::string> mapValue;
28399 std::vector<std::pair<std::string, std::string> > vOrderForm;
28400 unsigned int fTimeReceivedIsTxTime;
28401 unsigned int nTimeReceived; // time received by this node
28402 char fFromMe;
28403 std::string strFromAccount;
28404 std::vector<char> vfSpent; // which outputs are already spent
28405
28406 // memory only
28407 mutable char fDebitCached;
28408 mutable char fCreditCached;
28409 mutable char fAvailableCreditCached;
28410 mutable char fChangeCached;
28411 mutable int64 nDebitCached;
28412 mutable int64 nCreditCached;
28413 mutable int64 nAvailableCreditCached;
28414 mutable int64 nChangeCached;
28415
28416 // memory only UI hints
28417 mutable unsigned int nTimeDisplayed;
28418 mutable int nLinesDisplayed;
28419 mutable char fConfirmedDisplayed;
28420
28421 CWalletTx()
28422 {
28423 Init(NULL);
28424 }
28425
28426 CWalletTx(const CWallet* pwalletIn)
28427 {
28428 Init(pwalletIn);
28429 }
28430
28431 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
28432 {
28433 Init(pwalletIn);
28434 }
28435
28436 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
28437 {
28438 Init(pwalletIn);
28439 }
28440
28441 void Init(const CWallet* pwalletIn)
28442 {
28443 pwallet = pwalletIn;
28444 vtxPrev.clear();
28445 mapValue.clear();
28446 vOrderForm.clear();
28447 fTimeReceivedIsTxTime = false;
28448 nTimeReceived = 0;
28449 fFromMe = false;
28450 strFromAccount.clear();
28451 vfSpent.clear();
28452 fDebitCached = false;
28453 fCreditCached = false;
28454 fAvailableCreditCached = false;
28455 fChangeCached = false;
28456 nDebitCached = 0;
28457 nCreditCached = 0;
28458 nAvailableCreditCached = 0;
28459 nChangeCached = 0;
28460 nTimeDisplayed = 0;
28461 nLinesDisplayed = 0;
28462 fConfirmedDisplayed = false;
28463 }
28464
28465 IMPLEMENT_SERIALIZE
28466 (
28467 CWalletTx* pthis = const_cast<CWalletTx*>(this);
28468 if (fRead)
28469 pthis->Init(NULL);
28470 char fSpent = false;
28471
28472 if (!fRead)
28473 {
28474 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
28475
28476 std::string str;
28477 BOOST_FOREACH(char f, vfSpent)
28478 {
28479 str += (f ? '1' : '0');
28480 if (f)
28481 fSpent = true;
28482 }
28483 pthis->mapValue["spent"] = str;
28484 }
28485
28486 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
28487 READWRITE(vtxPrev);
28488 READWRITE(mapValue);
28489 READWRITE(vOrderForm);
28490 READWRITE(fTimeReceivedIsTxTime);
28491 READWRITE(nTimeReceived);
28492 READWRITE(fFromMe);
28493 READWRITE(fSpent);
28494
28495 if (fRead)
28496 {
28497 pthis->strFromAccount = pthis->mapValue["fromaccount"];
28498
28499 if (mapValue.count("spent"))
28500 BOOST_FOREACH(char c, pthis->mapValue["spent"])
28501 pthis->vfSpent.push_back(c != '0');
28502 else
28503 pthis->vfSpent.assign(vout.size(), fSpent);
28504 }
28505
28506 pthis->mapValue.erase("fromaccount");
28507 pthis->mapValue.erase("version");
28508 pthis->mapValue.erase("spent");
28509 )
28510
28511 // marks certain txout's as spent
28512 // returns true if any update took place
28513 bool UpdateSpent(const std::vector<char>& vfNewSpent)
28514 {
28515 bool fReturn = false;
28516 for (int i=0; i < vfNewSpent.size(); i++)
28517 {
28518 if (i == vfSpent.size())
28519 break;
28520
28521 if (vfNewSpent[i] && !vfSpent[i])
28522 {
28523 vfSpent[i] = true;
28524 fReturn = true;
28525 fAvailableCreditCached = false;
28526 }
28527 }
28528 return fReturn;
28529 }
28530
28531 // make sure balances are recalculated
28532 void MarkDirty()
28533 {
28534 fCreditCached = false;
28535 fAvailableCreditCached = false;
28536 fDebitCached = false;
28537 fChangeCached = false;
28538 }
28539
28540 void MarkSpent(unsigned int nOut)
28541 {
28542 if (nOut >= vout.size())
28543 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
28544 vfSpent.resize(vout.size());
28545 if (!vfSpent[nOut])
28546 {
28547 vfSpent[nOut] = true;
28548 fAvailableCreditCached = false;
28549 }
28550 }
28551
28552 bool IsSpent(unsigned int nOut) const
28553 {
28554 if (nOut >= vout.size())
28555 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
28556 if (nOut >= vfSpent.size())
28557 return false;
28558 return (!!vfSpent[nOut]);
28559 }
28560
28561 int64 GetDebit() const
28562 {
28563 if (vin.empty())
28564 return 0;
28565 if (fDebitCached)
28566 return nDebitCached;
28567 nDebitCached = pwallet->GetDebit(*this);
28568 fDebitCached = true;
28569 return nDebitCached;
28570 }
28571
28572 int64 GetCredit(bool fUseCache=true) const
28573 {
28574 // Must wait until coinbase is safely deep enough in the chain before valuing it
28575 if (IsCoinBase() && GetBlocksToMaturity() > 0)
28576 return 0;
28577
28578 // GetBalance can assume transactions in mapWallet won't change
28579 if (fUseCache && fCreditCached)
28580 return nCreditCached;
28581 nCreditCached = pwallet->GetCredit(*this);
28582 fCreditCached = true;
28583 return nCreditCached;
28584 }
28585
28586 int64 GetAvailableCredit(bool fUseCache=true) const
28587 {
28588 // Must wait until coinbase is safely deep enough in the chain before valuing it
28589 if (IsCoinBase() && GetBlocksToMaturity() > 0)
28590 return 0;
28591
28592 if (fUseCache && fAvailableCreditCached)
28593 return nAvailableCreditCached;
28594
28595 int64 nCredit = 0;
28596 for (int i = 0; i < vout.size(); i++)
28597 {
28598 if (!IsSpent(i))
28599 {
28600 const CTxOut &txout = vout[i];
28601 nCredit += pwallet->GetCredit(txout);
28602 if (!MoneyRange(nCredit))
28603 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
28604 }
28605 }
28606
28607 nAvailableCreditCached = nCredit;
28608 fAvailableCreditCached = true;
28609 return nCredit;
28610 }
28611
28612
28613 int64 GetChange() const
28614 {
28615 if (fChangeCached)
28616 return nChangeCached;
28617 nChangeCached = pwallet->GetChange(*this);
28618 fChangeCached = true;
28619 return nChangeCached;
28620 }
28621
28622 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
28623 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
28624
28625 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
28626 int64& nSent, int64& nFee) const;
28627
28628 bool IsFromMe() const
28629 {
28630 return (GetDebit() > 0);
28631 }
28632
28633 bool IsConfirmed() const
28634 {
28635 // Quick answer in most cases
28636 if (!IsFinal())
28637 return false;
28638 if (GetDepthInMainChain() >= 1)
28639 return true;
28640 if (!IsFromMe()) // using wtx's cached debit
28641 return false;
28642
28643 // If no confirmations but it's from us, we can still
28644 // consider it confirmed if all dependencies are confirmed
28645 std::map<uint256, const CMerkleTx*> mapPrev;
28646 std::vector<const CMerkleTx*> vWorkQueue;
28647 vWorkQueue.reserve(vtxPrev.size()+1);
28648 vWorkQueue.push_back(this);
28649 for (int i = 0; i < vWorkQueue.size(); i++)
28650 {
28651 const CMerkleTx* ptx = vWorkQueue[i];
28652
28653 if (!ptx->IsFinal())
28654 return false;
28655 if (ptx->GetDepthInMainChain() >= 1)
28656 continue;
28657 if (!pwallet->IsFromMe(*ptx))
28658 return false;
28659
28660 if (mapPrev.empty())
28661 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
28662 mapPrev[tx.GetHash()] = &tx;
28663
28664 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
28665 {
28666 if (!mapPrev.count(txin.prevout.hash))
28667 return false;
28668 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
28669 }
28670 }
28671 return true;
28672 }
28673
28674 bool WriteToDisk();
28675
28676 int64 GetTxTime() const;
28677 int GetRequestCount() const;
28678
28679 void AddSupportingTransactions(CTxDB& txdb);
28680
28681 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
28682 bool AcceptWalletTransaction();
28683
28684 void RelayWalletTransaction(CTxDB& txdb);
28685 void RelayWalletTransaction();
28686 };
28687
28688
28689 //
28690 // Private key that includes an expiration date in case it never gets used.
28691 //
28692 class CWalletKey
28693 {
28694 public:
28695 CPrivKey vchPrivKey;
28696 int64 nTimeCreated;
28697 int64 nTimeExpires;
28698 std::string strComment;
28699 //// todo: add something to note what created it (user, getnewaddress, change)
28700 //// maybe should have a map<string, string> property map
28701
28702 CWalletKey(int64 nExpires=0)
28703 {
28704 nTimeCreated = (nExpires ? GetTime() : 0);
28705 nTimeExpires = nExpires;
28706 }
28707
28708 IMPLEMENT_SERIALIZE
28709 (
28710 if (!(nType & SER_GETHASH))
28711 READWRITE(nVersion);
28712 READWRITE(vchPrivKey);
28713 READWRITE(nTimeCreated);
28714 READWRITE(nTimeExpires);
28715 READWRITE(strComment);
28716 )
28717 };
28718
28719
28720
28721
28722
28723
28724 //
28725 // Account information.
28726 // Stored in wallet with key "acc"+string account name
28727 //
28728 class CAccount
28729 {
28730 public:
28731 std::vector<unsigned char> vchPubKey;
28732
28733 CAccount()
28734 {
28735 SetNull();
28736 }
28737
28738 void SetNull()
28739 {
28740 vchPubKey.clear();
28741 }
28742
28743 IMPLEMENT_SERIALIZE
28744 (
28745 if (!(nType & SER_GETHASH))
28746 READWRITE(nVersion);
28747 READWRITE(vchPubKey);
28748 )
28749 };
28750
28751
28752
28753 //
28754 // Internal transfers.
28755 // Database key is acentry<account><counter>
28756 //
28757 class CAccountingEntry
28758 {
28759 public:
28760 std::string strAccount;
28761 int64 nCreditDebit;
28762 int64 nTime;
28763 std::string strOtherAccount;
28764 std::string strComment;
28765
28766 CAccountingEntry()
28767 {
28768 SetNull();
28769 }
28770
28771 void SetNull()
28772 {
28773 nCreditDebit = 0;
28774 nTime = 0;
28775 strAccount.clear();
28776 strOtherAccount.clear();
28777 strComment.clear();
28778 }
28779
28780 IMPLEMENT_SERIALIZE
28781 (
28782 if (!(nType & SER_GETHASH))
28783 READWRITE(nVersion);
28784 // Note: strAccount is serialized as part of the key, not here.
28785 READWRITE(nCreditDebit);
28786 READWRITE(nTime);
28787 READWRITE(strOtherAccount);
28788 READWRITE(strComment);
28789 )
28790 };
28791
28792 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
28793
28794 #endif