1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Copyright (c) 2012-2013 The NovaCoin developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #ifndef BITCOIN_WALLET_H
8 #define BITCOIN_WALLET_H
15 extern bool fWalletUnlockMintOnly;
21 /** (client) version numbers for particular wallet features */
24 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
26 FEATURE_WALLETCRYPT = 40000, // wallet encryption
27 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
29 FEATURE_LATEST = 60000
33 /** A key pool entry */
38 std::vector<unsigned char> vchPubKey;
45 CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
48 vchPubKey = vchPubKeyIn;
53 if (!(nType & SER_GETHASH))
60 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
61 * and provides the ability to create new transactions.
63 class CWallet : public CCryptoKeyStore
66 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
67 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
69 CWalletDB *pwalletdbEncryption;
71 // the current wallet version: clients below this version are not able to load the wallet
74 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
75 int nWalletMaxVersion;
78 mutable CCriticalSection cs_wallet;
81 std::string strWalletFile;
83 std::set<int64> setKeyPool;
86 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
87 MasterKeyMap mapMasterKeys;
88 unsigned int nMasterKeyMaxID;
92 nWalletVersion = FEATURE_BASE;
93 nWalletMaxVersion = FEATURE_BASE;
96 pwalletdbEncryption = NULL;
98 CWallet(std::string strWalletFileIn)
100 nWalletVersion = FEATURE_BASE;
101 nWalletMaxVersion = FEATURE_BASE;
102 strWalletFile = strWalletFileIn;
105 pwalletdbEncryption = NULL;
108 std::map<uint256, CWalletTx> mapWallet;
109 std::vector<uint256> vWalletUpdated;
111 std::map<uint256, int> mapRequestCount;
113 std::map<CBitcoinAddress, std::string> mapAddressBook;
115 std::vector<unsigned char> vchDefaultKey;
117 // check whether we are allowed to upgrade (or already support) to the named feature
118 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
120 // keystore implementation
121 // Generate a new key
122 std::vector<unsigned char> GenerateNewKey(bool bCompressed);
123 // Adds a key to the store, and saves it to disk.
124 bool AddKey(const CKey& key);
125 // Adds a key to the store, without saving it to disk (used by LoadWallet)
126 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
128 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
130 // Adds an encrypted key to the store, and saves it to disk.
131 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
132 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
133 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
134 bool AddCScript(const CScript& redeemScript);
135 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
137 bool Unlock(const SecureString& strWalletPassphrase);
138 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
139 bool EncryptWallet(const SecureString& strWalletPassphrase);
142 bool AddToWallet(const CWalletTx& wtxIn);
143 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
144 bool EraseFromWallet(uint256 hash);
145 void WalletUpdateSpent(const CTransaction& prevout);
146 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
147 int ScanForWalletTransaction(const uint256& hashTx);
148 void ReacceptWalletTransactions();
149 void ResendWalletTransactions();
150 int64 GetBalance() const;
151 int64 GetUnconfirmedBalance() const;
152 int64 GetStake() const;
153 int64 GetNewMint() const;
154 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
155 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
156 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
157 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
158 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
159 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
163 int64 AddReserveKey(const CKeyPool& keypool);
164 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
165 void KeepKey(int64 nIndex);
166 void ReturnKey(int64 nIndex);
167 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
168 int64 GetOldestKeyPoolTime();
169 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
171 bool IsMine(const CTxIn& txin) const;
172 int64 GetDebit(const CTxIn& txin) const;
173 bool IsMine(const CTxOut& txout) const
175 return ::IsMine(*this, txout.scriptPubKey);
177 int64 GetCredit(const CTxOut& txout) const
179 if (!MoneyRange(txout.nValue))
180 throw std::runtime_error("CWallet::GetCredit() : value out of range");
181 return (IsMine(txout) ? txout.nValue : 0);
183 bool IsChange(const CTxOut& txout) const;
184 int64 GetChange(const CTxOut& txout) const
186 if (!MoneyRange(txout.nValue))
187 throw std::runtime_error("CWallet::GetChange() : value out of range");
188 return (IsChange(txout) ? txout.nValue : 0);
190 bool IsMine(const CTransaction& tx) const
192 BOOST_FOREACH(const CTxOut& txout, tx.vout)
197 bool IsFromMe(const CTransaction& tx) const
199 return (GetDebit(tx) > 0);
201 int64 GetDebit(const CTransaction& tx) const
204 BOOST_FOREACH(const CTxIn& txin, tx.vin)
206 nDebit += GetDebit(txin);
207 if (!MoneyRange(nDebit))
208 throw std::runtime_error("CWallet::GetDebit() : value out of range");
212 int64 GetCredit(const CTransaction& tx) const
215 BOOST_FOREACH(const CTxOut& txout, tx.vout)
217 nCredit += GetCredit(txout);
218 if (!MoneyRange(nCredit))
219 throw std::runtime_error("CWallet::GetCredit() : value out of range");
223 int64 GetChange(const CTransaction& tx) const
226 BOOST_FOREACH(const CTxOut& txout, tx.vout)
228 nChange += GetChange(txout);
229 if (!MoneyRange(nChange))
230 throw std::runtime_error("CWallet::GetChange() : value out of range");
234 void SetBestChain(const CBlockLocator& loc);
236 int LoadWallet(bool& fFirstRunRet);
238 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
240 bool DelAddressBookName(const CBitcoinAddress& address);
242 void UpdatedTransaction(const uint256 &hashTx)
246 vWalletUpdated.push_back(hashTx);
250 void PrintWallet(const CBlock& block);
252 void Inventory(const uint256 &hash)
256 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
257 if (mi != mapRequestCount.end())
264 return setKeyPool.size();
267 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
269 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
271 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
272 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
274 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
275 bool SetMaxVersion(int nVersion);
277 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
278 int GetVersion() { return nWalletVersion; }
280 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
281 void DisableTransaction(const CTransaction &tx);
284 /** A key allocated from the key pool. */
290 std::vector<unsigned char> vchPubKey;
292 CReserveKey(CWallet* pwalletIn)
305 std::vector<unsigned char> GetReservedKey();
310 /** A transaction with a bunch of additional info that only the owner cares about.
311 * It includes any unrecorded transactions needed to link it back to the block chain.
313 class CWalletTx : public CMerkleTx
316 const CWallet* pwallet;
319 std::vector<CMerkleTx> vtxPrev;
320 std::map<std::string, std::string> mapValue;
321 std::vector<std::pair<std::string, std::string> > vOrderForm;
322 unsigned int fTimeReceivedIsTxTime;
323 unsigned int nTimeReceived; // time received by this node
325 std::string strFromAccount;
326 std::vector<char> vfSpent; // which outputs are already spent
329 mutable bool fDebitCached;
330 mutable bool fCreditCached;
331 mutable bool fAvailableCreditCached;
332 mutable bool fChangeCached;
333 mutable int64 nDebitCached;
334 mutable int64 nCreditCached;
335 mutable int64 nAvailableCreditCached;
336 mutable int64 nChangeCached;
343 CWalletTx(const CWallet* pwalletIn)
348 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
353 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
358 void Init(const CWallet* pwalletIn)
364 fTimeReceivedIsTxTime = false;
367 strFromAccount.clear();
369 fDebitCached = false;
370 fCreditCached = false;
371 fAvailableCreditCached = false;
372 fChangeCached = false;
375 nAvailableCreditCached = 0;
381 CWalletTx* pthis = const_cast<CWalletTx*>(this);
388 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
391 BOOST_FOREACH(char f, vfSpent)
393 str += (f ? '1' : '0');
397 pthis->mapValue["spent"] = str;
400 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
403 READWRITE(vOrderForm);
404 READWRITE(fTimeReceivedIsTxTime);
405 READWRITE(nTimeReceived);
411 pthis->strFromAccount = pthis->mapValue["fromaccount"];
413 if (mapValue.count("spent"))
414 BOOST_FOREACH(char c, pthis->mapValue["spent"])
415 pthis->vfSpent.push_back(c != '0');
417 pthis->vfSpent.assign(vout.size(), fSpent);
420 pthis->mapValue.erase("fromaccount");
421 pthis->mapValue.erase("version");
422 pthis->mapValue.erase("spent");
425 // marks certain txout's as spent
426 // returns true if any update took place
427 bool UpdateSpent(const std::vector<char>& vfNewSpent)
429 bool fReturn = false;
430 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
432 if (i == vfSpent.size())
435 if (vfNewSpent[i] && !vfSpent[i])
439 fAvailableCreditCached = false;
445 // make sure balances are recalculated
448 fCreditCached = false;
449 fAvailableCreditCached = false;
450 fDebitCached = false;
451 fChangeCached = false;
454 void BindWallet(CWallet *pwalletIn)
460 void MarkSpent(unsigned int nOut)
462 if (nOut >= vout.size())
463 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
464 vfSpent.resize(vout.size());
467 vfSpent[nOut] = true;
468 fAvailableCreditCached = false;
472 void MarkUnspent(unsigned int nOut)
474 if (nOut >= vout.size())
475 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
476 vfSpent.resize(vout.size());
479 vfSpent[nOut] = false;
480 fAvailableCreditCached = false;
484 bool IsSpent(unsigned int nOut) const
486 if (nOut >= vout.size())
487 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
488 if (nOut >= vfSpent.size())
490 return (!!vfSpent[nOut]);
493 int64 GetDebit() const
499 nDebitCached = pwallet->GetDebit(*this);
504 int64 GetCredit(bool fUseCache=true) const
506 // Must wait until coinbase is safely deep enough in the chain before valuing it
507 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
510 // GetBalance can assume transactions in mapWallet won't change
511 if (fUseCache && fCreditCached)
512 return nCreditCached;
513 nCreditCached = pwallet->GetCredit(*this);
514 fCreditCached = true;
515 return nCreditCached;
518 int64 GetAvailableCredit(bool fUseCache=true) const
520 // Must wait until coinbase is safely deep enough in the chain before valuing it
521 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
524 if (fUseCache && fAvailableCreditCached)
525 return nAvailableCreditCached;
528 for (unsigned int i = 0; i < vout.size(); i++)
532 const CTxOut &txout = vout[i];
533 nCredit += pwallet->GetCredit(txout);
534 if (!MoneyRange(nCredit))
535 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
539 nAvailableCreditCached = nCredit;
540 fAvailableCreditCached = true;
545 int64 GetChange() const
548 return nChangeCached;
549 nChangeCached = pwallet->GetChange(*this);
550 fChangeCached = true;
551 return nChangeCached;
554 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
555 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
557 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
558 int64& nSent, int64& nFee) const;
560 bool IsFromMe() const
562 return (GetDebit() > 0);
565 bool IsConfirmed() const
567 // Quick answer in most cases
570 if (GetDepthInMainChain() >= 1)
572 if (!IsFromMe()) // using wtx's cached debit
575 // If no confirmations but it's from us, we can still
576 // consider it confirmed if all dependencies are confirmed
577 std::map<uint256, const CMerkleTx*> mapPrev;
578 std::vector<const CMerkleTx*> vWorkQueue;
579 vWorkQueue.reserve(vtxPrev.size()+1);
580 vWorkQueue.push_back(this);
581 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
583 const CMerkleTx* ptx = vWorkQueue[i];
587 if (ptx->GetDepthInMainChain() >= 1)
589 if (!pwallet->IsFromMe(*ptx))
594 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
595 mapPrev[tx.GetHash()] = &tx;
598 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
600 if (!mapPrev.count(txin.prevout.hash))
602 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
610 int64 GetTxTime() const;
611 int GetRequestCount() const;
613 void AddSupportingTransactions(CTxDB& txdb);
615 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
616 bool AcceptWalletTransaction();
618 void RelayWalletTransaction(CTxDB& txdb);
619 void RelayWalletTransaction();
623 /** Private key that includes an expiration date in case it never gets used. */
630 std::string strComment;
631 //// todo: add something to note what created it (user, getnewaddress, change)
632 //// maybe should have a map<string, string> property map
634 CWalletKey(int64 nExpires=0)
636 nTimeCreated = (nExpires ? GetTime() : 0);
637 nTimeExpires = nExpires;
642 if (!(nType & SER_GETHASH))
644 READWRITE(vchPrivKey);
645 READWRITE(nTimeCreated);
646 READWRITE(nTimeExpires);
647 READWRITE(strComment);
656 /** Account information.
657 * Stored in wallet with key "acc"+string account name.
662 std::vector<unsigned char> vchPubKey;
676 if (!(nType & SER_GETHASH))
678 READWRITE(vchPubKey);
684 /** Internal transfers.
685 * Database key is acentry<account><counter>.
687 class CAccountingEntry
690 std::string strAccount;
693 std::string strOtherAccount;
694 std::string strComment;
706 strOtherAccount.clear();
712 if (!(nType & SER_GETHASH))
714 // Note: strAccount is serialized as part of the key, not here.
715 READWRITE(nCreditDebit);
717 READWRITE(strOtherAccount);
718 READWRITE(strComment);
722 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);