1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_WALLET_H
7 #define BITCOIN_WALLET_H
14 extern bool fWalletUnlockMintOnly;
20 /** (client) version numbers for particular wallet features */
23 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
25 FEATURE_WALLETCRYPT = 40000, // wallet encryption
26 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
28 FEATURE_LATEST = 60000
32 /** A key pool entry */
37 std::vector<unsigned char> vchPubKey;
44 CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
47 vchPubKey = vchPubKeyIn;
52 if (!(nType & SER_GETHASH))
59 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
60 * and provides the ability to create new transactions.
62 class CWallet : public CCryptoKeyStore
65 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
66 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
68 CWalletDB *pwalletdbEncryption;
70 // the current wallet version: clients below this version are not able to load the wallet
73 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
74 int nWalletMaxVersion;
77 mutable CCriticalSection cs_wallet;
80 std::string strWalletFile;
82 std::set<int64> setKeyPool;
85 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
86 MasterKeyMap mapMasterKeys;
87 unsigned int nMasterKeyMaxID;
91 nWalletVersion = FEATURE_BASE;
92 nWalletMaxVersion = FEATURE_BASE;
95 pwalletdbEncryption = NULL;
97 CWallet(std::string strWalletFileIn)
99 nWalletVersion = FEATURE_BASE;
100 nWalletMaxVersion = FEATURE_BASE;
101 strWalletFile = strWalletFileIn;
104 pwalletdbEncryption = NULL;
107 std::map<uint256, CWalletTx> mapWallet;
108 std::vector<uint256> vWalletUpdated;
110 std::map<uint256, int> mapRequestCount;
112 std::map<CBitcoinAddress, std::string> mapAddressBook;
114 std::vector<unsigned char> vchDefaultKey;
116 // check whether we are allowed to upgrade (or already support) to the named feature
117 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
119 // keystore implementation
120 // Generate a new key
121 std::vector<unsigned char> GenerateNewKey(bool bCompressed);
122 // Adds a key to the store, and saves it to disk.
123 bool AddKey(const CKey& key);
124 // Adds a key to the store, without saving it to disk (used by LoadWallet)
125 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
127 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
129 // Adds an encrypted key to the store, and saves it to disk.
130 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
131 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
132 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
133 bool AddCScript(const CScript& redeemScript);
134 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
136 bool Unlock(const SecureString& strWalletPassphrase);
137 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
138 bool EncryptWallet(const SecureString& strWalletPassphrase);
141 bool AddToWallet(const CWalletTx& wtxIn);
142 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
143 bool EraseFromWallet(uint256 hash);
144 void WalletUpdateSpent(const CTransaction& prevout);
145 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
146 int ScanForWalletTransaction(const uint256& hashTx);
147 void ReacceptWalletTransactions();
148 void ResendWalletTransactions();
149 int64 GetBalance() const;
150 int64 GetUnconfirmedBalance() const;
151 int64 GetStake() const;
152 int64 GetNewMint() const;
153 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
154 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
155 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
156 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
157 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
158 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
162 int64 AddReserveKey(const CKeyPool& keypool);
163 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
164 void KeepKey(int64 nIndex);
165 void ReturnKey(int64 nIndex);
166 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
167 int64 GetOldestKeyPoolTime();
168 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
170 bool IsMine(const CTxIn& txin) const;
171 int64 GetDebit(const CTxIn& txin) const;
172 bool IsMine(const CTxOut& txout) const
174 return ::IsMine(*this, txout.scriptPubKey);
176 int64 GetCredit(const CTxOut& txout) const
178 if (!MoneyRange(txout.nValue))
179 throw std::runtime_error("CWallet::GetCredit() : value out of range");
180 return (IsMine(txout) ? txout.nValue : 0);
182 bool IsChange(const CTxOut& txout) const;
183 int64 GetChange(const CTxOut& txout) const
185 if (!MoneyRange(txout.nValue))
186 throw std::runtime_error("CWallet::GetChange() : value out of range");
187 return (IsChange(txout) ? txout.nValue : 0);
189 bool IsMine(const CTransaction& tx) const
191 BOOST_FOREACH(const CTxOut& txout, tx.vout)
196 bool IsFromMe(const CTransaction& tx) const
198 return (GetDebit(tx) > 0);
200 int64 GetDebit(const CTransaction& tx) const
203 BOOST_FOREACH(const CTxIn& txin, tx.vin)
205 nDebit += GetDebit(txin);
206 if (!MoneyRange(nDebit))
207 throw std::runtime_error("CWallet::GetDebit() : value out of range");
211 int64 GetCredit(const CTransaction& tx) const
214 BOOST_FOREACH(const CTxOut& txout, tx.vout)
216 nCredit += GetCredit(txout);
217 if (!MoneyRange(nCredit))
218 throw std::runtime_error("CWallet::GetCredit() : value out of range");
222 int64 GetChange(const CTransaction& tx) const
225 BOOST_FOREACH(const CTxOut& txout, tx.vout)
227 nChange += GetChange(txout);
228 if (!MoneyRange(nChange))
229 throw std::runtime_error("CWallet::GetChange() : value out of range");
233 void SetBestChain(const CBlockLocator& loc);
235 int LoadWallet(bool& fFirstRunRet);
237 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
239 bool DelAddressBookName(const CBitcoinAddress& address);
241 void UpdatedTransaction(const uint256 &hashTx)
245 vWalletUpdated.push_back(hashTx);
249 void PrintWallet(const CBlock& block);
251 void Inventory(const uint256 &hash)
255 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
256 if (mi != mapRequestCount.end())
263 return setKeyPool.size();
266 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
268 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
270 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
271 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
273 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
274 bool SetMaxVersion(int nVersion);
276 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
277 int GetVersion() { return nWalletVersion; }
279 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
280 void DisableTransaction(const CTransaction &tx);
283 /** A key allocated from the key pool. */
289 std::vector<unsigned char> vchPubKey;
291 CReserveKey(CWallet* pwalletIn)
304 std::vector<unsigned char> GetReservedKey();
309 /** A transaction with a bunch of additional info that only the owner cares about.
310 * It includes any unrecorded transactions needed to link it back to the block chain.
312 class CWalletTx : public CMerkleTx
315 const CWallet* pwallet;
318 std::vector<CMerkleTx> vtxPrev;
319 std::map<std::string, std::string> mapValue;
320 std::vector<std::pair<std::string, std::string> > vOrderForm;
321 unsigned int fTimeReceivedIsTxTime;
322 unsigned int nTimeReceived; // time received by this node
324 std::string strFromAccount;
325 std::vector<char> vfSpent; // which outputs are already spent
328 mutable bool fDebitCached;
329 mutable bool fCreditCached;
330 mutable bool fAvailableCreditCached;
331 mutable bool fChangeCached;
332 mutable int64 nDebitCached;
333 mutable int64 nCreditCached;
334 mutable int64 nAvailableCreditCached;
335 mutable int64 nChangeCached;
342 CWalletTx(const CWallet* pwalletIn)
347 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
352 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
357 void Init(const CWallet* pwalletIn)
363 fTimeReceivedIsTxTime = false;
366 strFromAccount.clear();
368 fDebitCached = false;
369 fCreditCached = false;
370 fAvailableCreditCached = false;
371 fChangeCached = false;
374 nAvailableCreditCached = 0;
380 CWalletTx* pthis = const_cast<CWalletTx*>(this);
387 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
390 BOOST_FOREACH(char f, vfSpent)
392 str += (f ? '1' : '0');
396 pthis->mapValue["spent"] = str;
399 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
402 READWRITE(vOrderForm);
403 READWRITE(fTimeReceivedIsTxTime);
404 READWRITE(nTimeReceived);
410 pthis->strFromAccount = pthis->mapValue["fromaccount"];
412 if (mapValue.count("spent"))
413 BOOST_FOREACH(char c, pthis->mapValue["spent"])
414 pthis->vfSpent.push_back(c != '0');
416 pthis->vfSpent.assign(vout.size(), fSpent);
419 pthis->mapValue.erase("fromaccount");
420 pthis->mapValue.erase("version");
421 pthis->mapValue.erase("spent");
424 // marks certain txout's as spent
425 // returns true if any update took place
426 bool UpdateSpent(const std::vector<char>& vfNewSpent)
428 bool fReturn = false;
429 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
431 if (i == vfSpent.size())
434 if (vfNewSpent[i] && !vfSpent[i])
438 fAvailableCreditCached = false;
444 // make sure balances are recalculated
447 fCreditCached = false;
448 fAvailableCreditCached = false;
449 fDebitCached = false;
450 fChangeCached = false;
453 void BindWallet(CWallet *pwalletIn)
459 void MarkSpent(unsigned int nOut)
461 if (nOut >= vout.size())
462 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
463 vfSpent.resize(vout.size());
466 vfSpent[nOut] = true;
467 fAvailableCreditCached = false;
471 void MarkUnspent(unsigned int nOut)
473 if (nOut >= vout.size())
474 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
475 vfSpent.resize(vout.size());
478 vfSpent[nOut] = false;
479 fAvailableCreditCached = false;
483 bool IsSpent(unsigned int nOut) const
485 if (nOut >= vout.size())
486 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
487 if (nOut >= vfSpent.size())
489 return (!!vfSpent[nOut]);
492 int64 GetDebit() const
498 nDebitCached = pwallet->GetDebit(*this);
503 int64 GetCredit(bool fUseCache=true) const
505 // Must wait until coinbase is safely deep enough in the chain before valuing it
506 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
509 // GetBalance can assume transactions in mapWallet won't change
510 if (fUseCache && fCreditCached)
511 return nCreditCached;
512 nCreditCached = pwallet->GetCredit(*this);
513 fCreditCached = true;
514 return nCreditCached;
517 int64 GetAvailableCredit(bool fUseCache=true) const
519 // Must wait until coinbase is safely deep enough in the chain before valuing it
520 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
523 if (fUseCache && fAvailableCreditCached)
524 return nAvailableCreditCached;
527 for (unsigned int i = 0; i < vout.size(); i++)
531 const CTxOut &txout = vout[i];
532 nCredit += pwallet->GetCredit(txout);
533 if (!MoneyRange(nCredit))
534 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
538 nAvailableCreditCached = nCredit;
539 fAvailableCreditCached = true;
544 int64 GetChange() const
547 return nChangeCached;
548 nChangeCached = pwallet->GetChange(*this);
549 fChangeCached = true;
550 return nChangeCached;
553 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
554 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
556 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
557 int64& nSent, int64& nFee) const;
559 bool IsFromMe() const
561 return (GetDebit() > 0);
564 bool IsConfirmed() const
566 // Quick answer in most cases
569 if (GetDepthInMainChain() >= 1)
571 if (!IsFromMe()) // using wtx's cached debit
574 // If no confirmations but it's from us, we can still
575 // consider it confirmed if all dependencies are confirmed
576 std::map<uint256, const CMerkleTx*> mapPrev;
577 std::vector<const CMerkleTx*> vWorkQueue;
578 vWorkQueue.reserve(vtxPrev.size()+1);
579 vWorkQueue.push_back(this);
580 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
582 const CMerkleTx* ptx = vWorkQueue[i];
586 if (ptx->GetDepthInMainChain() >= 1)
588 if (!pwallet->IsFromMe(*ptx))
593 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
594 mapPrev[tx.GetHash()] = &tx;
597 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
599 if (!mapPrev.count(txin.prevout.hash))
601 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
609 int64 GetTxTime() const;
610 int GetRequestCount() const;
612 void AddSupportingTransactions(CTxDB& txdb);
614 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
615 bool AcceptWalletTransaction();
617 void RelayWalletTransaction(CTxDB& txdb);
618 void RelayWalletTransaction();
622 /** Private key that includes an expiration date in case it never gets used. */
629 std::string strComment;
630 //// todo: add something to note what created it (user, getnewaddress, change)
631 //// maybe should have a map<string, string> property map
633 CWalletKey(int64 nExpires=0)
635 nTimeCreated = (nExpires ? GetTime() : 0);
636 nTimeExpires = nExpires;
641 if (!(nType & SER_GETHASH))
643 READWRITE(vchPrivKey);
644 READWRITE(nTimeCreated);
645 READWRITE(nTimeExpires);
646 READWRITE(strComment);
655 /** Account information.
656 * Stored in wallet with key "acc"+string account name.
661 std::vector<unsigned char> vchPubKey;
675 if (!(nType & SER_GETHASH))
677 READWRITE(vchPubKey);
683 /** Internal transfers.
684 * Database key is acentry<account><counter>.
686 class CAccountingEntry
689 std::string strAccount;
692 std::string strOtherAccount;
693 std::string strComment;
705 strOtherAccount.clear();
711 if (!(nType & SER_GETHASH))
713 // Note: strAccount is serialized as part of the key, not here.
714 READWRITE(nCreditDebit);
716 READWRITE(strOtherAccount);
717 READWRITE(strComment);
721 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);