-
+ DF93B83C3880E14D890FE853D8556EEC6377B90D5E83BD696F4C5800042C2CD04C5242B69B8886E22DFCEB5B9B16E790FB526E9039CC130C9FB0F12CC8BB19D2
bitcoin/src/wallet.h
(0 . 0)(1 . 645)
26042 // Copyright (c) 2009-2010 Satoshi Nakamoto
26043 // Copyright (c) 2009-2012 The Bitcoin developers
26044 // Distributed under the MIT/X11 software license, see the accompanying
26045 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
26046 #ifndef BITCOIN_WALLET_H
26047 #define BITCOIN_WALLET_H
26048
26049 #include "bignum.h"
26050 #include "key.h"
26051 #include "script.h"
26052
26053 class CWalletTx;
26054 class CReserveKey;
26055 class CWalletDB;
26056
26057 // A CWallet is an extension of a keystore, which also maintains a set of
26058 // transactions and balances, and provides the ability to create new
26059 // transactions
26060 class CWallet : public CCryptoKeyStore
26061 {
26062 private:
26063 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26064 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26065
26066 CWalletDB *pwalletdbEncryption;
26067
26068 public:
26069 mutable CCriticalSection cs_wallet;
26070
26071 bool fFileBacked;
26072 std::string strWalletFile;
26073
26074 std::set<int64> setKeyPool;
26075
26076 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
26077 MasterKeyMap mapMasterKeys;
26078 unsigned int nMasterKeyMaxID;
26079
26080 CWallet()
26081 {
26082 fFileBacked = false;
26083 nMasterKeyMaxID = 0;
26084 pwalletdbEncryption = NULL;
26085 }
26086 CWallet(std::string strWalletFileIn)
26087 {
26088 strWalletFile = strWalletFileIn;
26089 fFileBacked = true;
26090 nMasterKeyMaxID = 0;
26091 pwalletdbEncryption = NULL;
26092 }
26093
26094 std::map<uint256, CWalletTx> mapWallet;
26095 std::vector<uint256> vWalletUpdated;
26096
26097 std::map<uint256, int> mapRequestCount;
26098
26099 std::map<CBitcoinAddress, std::string> mapAddressBook;
26100
26101 std::vector<unsigned char> vchDefaultKey;
26102
26103 // keystore implementation
26104 // Adds a key to the store, and saves it to disk.
26105 bool AddKey(const CKey& key);
26106 // Adds a key to the store, without saving it to disk (used by LoadWallet)
26107 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
26108
26109 // Adds an encrypted key to the store, and saves it to disk.
26110 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
26111 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
26112 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
26113
26114 bool Unlock(const SecureString& strWalletPassphrase);
26115 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
26116 bool EncryptWallet(const SecureString& strWalletPassphrase);
26117
26118 bool AddToWallet(const CWalletTx& wtxIn);
26119 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
26120 bool EraseFromWallet(uint256 hash);
26121 void WalletUpdateSpent(const CTransaction& prevout);
26122 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
26123 void ReacceptWalletTransactions();
26124 void ResendWalletTransactions();
26125 int64 GetBalance() const;
26126 int64 GetUnconfirmedBalance() const;
26127 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
26128 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
26129 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
26130 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
26131 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
26132
26133 bool NewKeyPool();
26134 bool TopUpKeyPool();
26135 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
26136 void KeepKey(int64 nIndex);
26137 void ReturnKey(int64 nIndex);
26138 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
26139 int64 GetOldestKeyPoolTime();
26140
26141 bool IsMine(const CTxIn& txin) const;
26142 int64 GetDebit(const CTxIn& txin) const;
26143 bool IsMine(const CTxOut& txout) const
26144 {
26145 return ::IsMine(*this, txout.scriptPubKey);
26146 }
26147 int64 GetCredit(const CTxOut& txout) const
26148 {
26149 if (!MoneyRange(txout.nValue))
26150 throw std::runtime_error("CWallet::GetCredit() : value out of range");
26151 return (IsMine(txout) ? txout.nValue : 0);
26152 }
26153 bool IsChange(const CTxOut& txout) const
26154 {
26155 CBitcoinAddress address;
26156 if (ExtractAddress(txout.scriptPubKey, this, address))
26157 CRITICAL_BLOCK(cs_wallet)
26158 if (!mapAddressBook.count(address))
26159 return true;
26160 return false;
26161 }
26162 int64 GetChange(const CTxOut& txout) const
26163 {
26164 if (!MoneyRange(txout.nValue))
26165 throw std::runtime_error("CWallet::GetChange() : value out of range");
26166 return (IsChange(txout) ? txout.nValue : 0);
26167 }
26168 bool IsMine(const CTransaction& tx) const
26169 {
26170 BOOST_FOREACH(const CTxOut& txout, tx.vout)
26171 if (IsMine(txout))
26172 return true;
26173 return false;
26174 }
26175 bool IsFromMe(const CTransaction& tx) const
26176 {
26177 return (GetDebit(tx) > 0);
26178 }
26179 int64 GetDebit(const CTransaction& tx) const
26180 {
26181 int64 nDebit = 0;
26182 BOOST_FOREACH(const CTxIn& txin, tx.vin)
26183 {
26184 nDebit += GetDebit(txin);
26185 if (!MoneyRange(nDebit))
26186 throw std::runtime_error("CWallet::GetDebit() : value out of range");
26187 }
26188 return nDebit;
26189 }
26190 int64 GetCredit(const CTransaction& tx) const
26191 {
26192 int64 nCredit = 0;
26193 BOOST_FOREACH(const CTxOut& txout, tx.vout)
26194 {
26195 nCredit += GetCredit(txout);
26196 if (!MoneyRange(nCredit))
26197 throw std::runtime_error("CWallet::GetCredit() : value out of range");
26198 }
26199 return nCredit;
26200 }
26201 int64 GetChange(const CTransaction& tx) const
26202 {
26203 int64 nChange = 0;
26204 BOOST_FOREACH(const CTxOut& txout, tx.vout)
26205 {
26206 nChange += GetChange(txout);
26207 if (!MoneyRange(nChange))
26208 throw std::runtime_error("CWallet::GetChange() : value out of range");
26209 }
26210 return nChange;
26211 }
26212 void SetBestChain(const CBlockLocator& loc)
26213 {
26214 CWalletDB walletdb(strWalletFile);
26215 walletdb.WriteBestBlock(loc);
26216 }
26217
26218 int LoadWallet(bool& fFirstRunRet);
26219 // bool BackupWallet(const std::string& strDest);
26220
26221 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
26222
26223 bool DelAddressBookName(const CBitcoinAddress& address);
26224
26225 void UpdatedTransaction(const uint256 &hashTx)
26226 {
26227 CRITICAL_BLOCK(cs_wallet)
26228 vWalletUpdated.push_back(hashTx);
26229 }
26230
26231 void PrintWallet(const CBlock& block);
26232
26233 void Inventory(const uint256 &hash)
26234 {
26235 CRITICAL_BLOCK(cs_wallet)
26236 {
26237 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
26238 if (mi != mapRequestCount.end())
26239 (*mi).second++;
26240 }
26241 }
26242
26243 int GetKeyPoolSize()
26244 {
26245 return setKeyPool.size();
26246 }
26247
26248 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
26249
26250 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
26251 };
26252
26253
26254 class CReserveKey
26255 {
26256 protected:
26257 CWallet* pwallet;
26258 int64 nIndex;
26259 std::vector<unsigned char> vchPubKey;
26260 public:
26261 CReserveKey(CWallet* pwalletIn)
26262 {
26263 nIndex = -1;
26264 pwallet = pwalletIn;
26265 }
26266
26267 ~CReserveKey()
26268 {
26269 if (!fShutdown)
26270 ReturnKey();
26271 }
26272
26273 void ReturnKey();
26274 std::vector<unsigned char> GetReservedKey();
26275 void KeepKey();
26276 };
26277
26278
26279 //
26280 // A transaction with a bunch of additional info that only the owner cares
26281 // about. It includes any unrecorded transactions needed to link it back
26282 // to the block chain.
26283 //
26284 class CWalletTx : public CMerkleTx
26285 {
26286 public:
26287 const CWallet* pwallet;
26288
26289 std::vector<CMerkleTx> vtxPrev;
26290 std::map<std::string, std::string> mapValue;
26291 std::vector<std::pair<std::string, std::string> > vOrderForm;
26292 unsigned int fTimeReceivedIsTxTime;
26293 unsigned int nTimeReceived; // time received by this node
26294 char fFromMe;
26295 std::string strFromAccount;
26296 std::vector<char> vfSpent; // which outputs are already spent
26297
26298 // memory only
26299 mutable char fDebitCached;
26300 mutable char fCreditCached;
26301 mutable char fAvailableCreditCached;
26302 mutable char fChangeCached;
26303 mutable int64 nDebitCached;
26304 mutable int64 nCreditCached;
26305 mutable int64 nAvailableCreditCached;
26306 mutable int64 nChangeCached;
26307
26308 // memory only UI hints
26309 mutable unsigned int nTimeDisplayed;
26310 mutable int nLinesDisplayed;
26311 mutable char fConfirmedDisplayed;
26312
26313 CWalletTx()
26314 {
26315 Init(NULL);
26316 }
26317
26318 CWalletTx(const CWallet* pwalletIn)
26319 {
26320 Init(pwalletIn);
26321 }
26322
26323 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
26324 {
26325 Init(pwalletIn);
26326 }
26327
26328 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
26329 {
26330 Init(pwalletIn);
26331 }
26332
26333 void Init(const CWallet* pwalletIn)
26334 {
26335 pwallet = pwalletIn;
26336 vtxPrev.clear();
26337 mapValue.clear();
26338 vOrderForm.clear();
26339 fTimeReceivedIsTxTime = false;
26340 nTimeReceived = 0;
26341 fFromMe = false;
26342 strFromAccount.clear();
26343 vfSpent.clear();
26344 fDebitCached = false;
26345 fCreditCached = false;
26346 fAvailableCreditCached = false;
26347 fChangeCached = false;
26348 nDebitCached = 0;
26349 nCreditCached = 0;
26350 nAvailableCreditCached = 0;
26351 nChangeCached = 0;
26352 nTimeDisplayed = 0;
26353 nLinesDisplayed = 0;
26354 fConfirmedDisplayed = false;
26355 }
26356
26357 IMPLEMENT_SERIALIZE
26358 (
26359 CWalletTx* pthis = const_cast<CWalletTx*>(this);
26360 if (fRead)
26361 pthis->Init(NULL);
26362 char fSpent = false;
26363
26364 if (!fRead)
26365 {
26366 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
26367
26368 std::string str;
26369 BOOST_FOREACH(char f, vfSpent)
26370 {
26371 str += (f ? '1' : '0');
26372 if (f)
26373 fSpent = true;
26374 }
26375 pthis->mapValue["spent"] = str;
26376 }
26377
26378 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
26379 READWRITE(vtxPrev);
26380 READWRITE(mapValue);
26381 READWRITE(vOrderForm);
26382 READWRITE(fTimeReceivedIsTxTime);
26383 READWRITE(nTimeReceived);
26384 READWRITE(fFromMe);
26385 READWRITE(fSpent);
26386
26387 if (fRead)
26388 {
26389 pthis->strFromAccount = pthis->mapValue["fromaccount"];
26390
26391 if (mapValue.count("spent"))
26392 BOOST_FOREACH(char c, pthis->mapValue["spent"])
26393 pthis->vfSpent.push_back(c != '0');
26394 else
26395 pthis->vfSpent.assign(vout.size(), fSpent);
26396 }
26397
26398 pthis->mapValue.erase("fromaccount");
26399 pthis->mapValue.erase("version");
26400 pthis->mapValue.erase("spent");
26401 )
26402
26403 // marks certain txout's as spent
26404 // returns true if any update took place
26405 bool UpdateSpent(const std::vector<char>& vfNewSpent)
26406 {
26407 bool fReturn = false;
26408 for (int i=0; i < vfNewSpent.size(); i++)
26409 {
26410 if (i == vfSpent.size())
26411 break;
26412
26413 if (vfNewSpent[i] && !vfSpent[i])
26414 {
26415 vfSpent[i] = true;
26416 fReturn = true;
26417 fAvailableCreditCached = false;
26418 }
26419 }
26420 return fReturn;
26421 }
26422
26423 // make sure balances are recalculated
26424 void MarkDirty()
26425 {
26426 fCreditCached = false;
26427 fAvailableCreditCached = false;
26428 fDebitCached = false;
26429 fChangeCached = false;
26430 }
26431
26432 void MarkSpent(unsigned int nOut)
26433 {
26434 if (nOut >= vout.size())
26435 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
26436 vfSpent.resize(vout.size());
26437 if (!vfSpent[nOut])
26438 {
26439 vfSpent[nOut] = true;
26440 fAvailableCreditCached = false;
26441 }
26442 }
26443
26444 bool IsSpent(unsigned int nOut) const
26445 {
26446 if (nOut >= vout.size())
26447 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
26448 if (nOut >= vfSpent.size())
26449 return false;
26450 return (!!vfSpent[nOut]);
26451 }
26452
26453 int64 GetDebit() const
26454 {
26455 if (vin.empty())
26456 return 0;
26457 if (fDebitCached)
26458 return nDebitCached;
26459 nDebitCached = pwallet->GetDebit(*this);
26460 fDebitCached = true;
26461 return nDebitCached;
26462 }
26463
26464 int64 GetCredit(bool fUseCache=true) const
26465 {
26466 // Must wait until coinbase is safely deep enough in the chain before valuing it
26467 if (IsCoinBase() && GetBlocksToMaturity() > 0)
26468 return 0;
26469
26470 // GetBalance can assume transactions in mapWallet won't change
26471 if (fUseCache && fCreditCached)
26472 return nCreditCached;
26473 nCreditCached = pwallet->GetCredit(*this);
26474 fCreditCached = true;
26475 return nCreditCached;
26476 }
26477
26478 int64 GetAvailableCredit(bool fUseCache=true) const
26479 {
26480 // Must wait until coinbase is safely deep enough in the chain before valuing it
26481 if (IsCoinBase() && GetBlocksToMaturity() > 0)
26482 return 0;
26483
26484 if (fUseCache && fAvailableCreditCached)
26485 return nAvailableCreditCached;
26486
26487 int64 nCredit = 0;
26488 for (int i = 0; i < vout.size(); i++)
26489 {
26490 if (!IsSpent(i))
26491 {
26492 const CTxOut &txout = vout[i];
26493 nCredit += pwallet->GetCredit(txout);
26494 if (!MoneyRange(nCredit))
26495 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
26496 }
26497 }
26498
26499 nAvailableCreditCached = nCredit;
26500 fAvailableCreditCached = true;
26501 return nCredit;
26502 }
26503
26504
26505 int64 GetChange() const
26506 {
26507 if (fChangeCached)
26508 return nChangeCached;
26509 nChangeCached = pwallet->GetChange(*this);
26510 fChangeCached = true;
26511 return nChangeCached;
26512 }
26513
26514 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
26515 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
26516
26517 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
26518 int64& nSent, int64& nFee) const;
26519
26520 bool IsFromMe() const
26521 {
26522 return (GetDebit() > 0);
26523 }
26524
26525 bool IsConfirmed() const
26526 {
26527 // Quick answer in most cases
26528 if (!IsFinal())
26529 return false;
26530 if (GetDepthInMainChain() >= 1)
26531 return true;
26532 if (!IsFromMe()) // using wtx's cached debit
26533 return false;
26534
26535 // If no confirmations but it's from us, we can still
26536 // consider it confirmed if all dependencies are confirmed
26537 std::map<uint256, const CMerkleTx*> mapPrev;
26538 std::vector<const CMerkleTx*> vWorkQueue;
26539 vWorkQueue.reserve(vtxPrev.size()+1);
26540 vWorkQueue.push_back(this);
26541 for (int i = 0; i < vWorkQueue.size(); i++)
26542 {
26543 const CMerkleTx* ptx = vWorkQueue[i];
26544
26545 if (!ptx->IsFinal())
26546 return false;
26547 if (ptx->GetDepthInMainChain() >= 1)
26548 continue;
26549 if (!pwallet->IsFromMe(*ptx))
26550 return false;
26551
26552 if (mapPrev.empty())
26553 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
26554 mapPrev[tx.GetHash()] = &tx;
26555
26556 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
26557 {
26558 if (!mapPrev.count(txin.prevout.hash))
26559 return false;
26560 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
26561 }
26562 }
26563 return true;
26564 }
26565
26566 bool WriteToDisk();
26567
26568 int64 GetTxTime() const;
26569 int GetRequestCount() const;
26570
26571 void AddSupportingTransactions(CTxDB& txdb);
26572
26573 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
26574 bool AcceptWalletTransaction();
26575
26576 void RelayWalletTransaction(CTxDB& txdb);
26577 void RelayWalletTransaction();
26578 };
26579
26580
26581 //
26582 // Private key that includes an expiration date in case it never gets used.
26583 //
26584 class CWalletKey
26585 {
26586 public:
26587 CPrivKey vchPrivKey;
26588 int64 nTimeCreated;
26589 int64 nTimeExpires;
26590 std::string strComment;
26591 //// todo: add something to note what created it (user, getnewaddress, change)
26592 //// maybe should have a map<string, string> property map
26593
26594 CWalletKey(int64 nExpires=0)
26595 {
26596 nTimeCreated = (nExpires ? GetTime() : 0);
26597 nTimeExpires = nExpires;
26598 }
26599
26600 IMPLEMENT_SERIALIZE
26601 (
26602 if (!(nType & SER_GETHASH))
26603 READWRITE(nVersion);
26604 READWRITE(vchPrivKey);
26605 READWRITE(nTimeCreated);
26606 READWRITE(nTimeExpires);
26607 READWRITE(strComment);
26608 )
26609 };
26610
26611
26612
26613
26614
26615
26616 //
26617 // Account information.
26618 // Stored in wallet with key "acc"+string account name
26619 //
26620 class CAccount
26621 {
26622 public:
26623 std::vector<unsigned char> vchPubKey;
26624
26625 CAccount()
26626 {
26627 SetNull();
26628 }
26629
26630 void SetNull()
26631 {
26632 vchPubKey.clear();
26633 }
26634
26635 IMPLEMENT_SERIALIZE
26636 (
26637 if (!(nType & SER_GETHASH))
26638 READWRITE(nVersion);
26639 READWRITE(vchPubKey);
26640 )
26641 };
26642
26643
26644
26645 //
26646 // Internal transfers.
26647 // Database key is acentry<account><counter>
26648 //
26649 class CAccountingEntry
26650 {
26651 public:
26652 std::string strAccount;
26653 int64 nCreditDebit;
26654 int64 nTime;
26655 std::string strOtherAccount;
26656 std::string strComment;
26657
26658 CAccountingEntry()
26659 {
26660 SetNull();
26661 }
26662
26663 void SetNull()
26664 {
26665 nCreditDebit = 0;
26666 nTime = 0;
26667 strAccount.clear();
26668 strOtherAccount.clear();
26669 strComment.clear();
26670 }
26671
26672 IMPLEMENT_SERIALIZE
26673 (
26674 if (!(nType & SER_GETHASH))
26675 READWRITE(nVersion);
26676 // Note: strAccount is serialized as part of the key, not here.
26677 READWRITE(nCreditDebit);
26678 READWRITE(nTime);
26679 READWRITE(strOtherAccount);
26680 READWRITE(strComment);
26681 )
26682 };
26683
26684 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
26685
26686 #endif