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
12 #include "ui_interface.h"
19 /** (client) version numbers for particular wallet features */
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 */
43 CKeyPool(const CPubKey
& vchPubKeyIn
)
46 vchPubKey
= vchPubKeyIn
;
51 if (!(nType
& SER_GETHASH
))
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
64 bool SelectCoins(int64 nTargetValue
, std::set
<std::pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, int64
& nValueRet
) const;
66 CWalletDB
*pwalletdbEncryption
;
68 // the current wallet version: clients below this version are not able to load the wallet
71 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
72 int nWalletMaxVersion
;
75 mutable CCriticalSection cs_wallet
;
78 std::string strWalletFile
;
80 std::set
<int64
> setKeyPool
;
83 typedef std::map
<unsigned int, CMasterKey
> MasterKeyMap
;
84 MasterKeyMap mapMasterKeys
;
85 unsigned int nMasterKeyMaxID
;
89 nWalletVersion
= FEATURE_BASE
;
90 nWalletMaxVersion
= FEATURE_BASE
;
93 pwalletdbEncryption
= NULL
;
95 CWallet(std::string strWalletFileIn
)
97 nWalletVersion
= FEATURE_BASE
;
98 nWalletMaxVersion
= FEATURE_BASE
;
99 strWalletFile
= strWalletFileIn
;
102 pwalletdbEncryption
= NULL
;
105 std::map
<uint256
, CWalletTx
> mapWallet
;
106 std::map
<uint256
, int> mapRequestCount
;
108 std::map
<CTxDestination
, std::string
> mapAddressBook
;
110 CPubKey vchDefaultKey
;
112 // check whether we are allowed to upgrade (or already support) to the named feature
113 bool CanSupportFeature(enum WalletFeature wf
) { return nWalletMaxVersion
>= wf
; }
115 void AvailableCoins(std::vector
<COutput
>& vCoins
, bool fOnlyConfirmed
=true) const;
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
);
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);
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
)
193 bool IsFromMe(const CTransaction
& tx
) const
195 return (GetDebit(tx
) > 0);
197 int64
GetDebit(const CTransaction
& tx
) const
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");
208 int64
GetCredit(const CTransaction
& tx
) const
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");
219 int64
GetChange(const CTransaction
& tx
) const
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");
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
)
246 std::map
<uint256
, int>::iterator mi
= mapRequestCount
.find(hash
);
247 if (mi
!= mapRequestCount
.end())
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. */
289 CReserveKey(CWallet
* pwalletIn
)
302 CPubKey
GetReservedKey();
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
313 const CWallet
* pwallet
;
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
322 std::string strFromAccount
;
323 std::vector
<char> vfSpent
; // which outputs are already spent
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
;
340 CWalletTx(const CWallet
* pwalletIn
)
345 CWalletTx(const CWallet
* pwalletIn
, const CMerkleTx
& txIn
) : CMerkleTx(txIn
)
350 CWalletTx(const CWallet
* pwalletIn
, const CTransaction
& txIn
) : CMerkleTx(txIn
)
355 void Init(const CWallet
* pwalletIn
)
361 fTimeReceivedIsTxTime
= false;
364 strFromAccount
.clear();
366 fDebitCached
= false;
367 fCreditCached
= false;
368 fAvailableCreditCached
= false;
369 fChangeCached
= false;
372 nAvailableCreditCached
= 0;
378 CWalletTx
* pthis
= const_cast<CWalletTx
*>(this);
385 pthis
->mapValue
["fromaccount"] = pthis
->strFromAccount
;
388 BOOST_FOREACH(char f
, vfSpent
)
390 str
+= (f
? '1' : '0');
394 pthis
->mapValue
["spent"] = str
;
397 nSerSize
+= SerReadWrite(s
, *(CMerkleTx
*)this, nType
, nVersion
,ser_action
);
400 READWRITE(vOrderForm
);
401 READWRITE(fTimeReceivedIsTxTime
);
402 READWRITE(nTimeReceived
);
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');
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())
432 if (vfNewSpent
[i
] && !vfSpent
[i
])
436 fAvailableCreditCached
= false;
442 // make sure balances are recalculated
445 fCreditCached
= false;
446 fAvailableCreditCached
= false;
447 fDebitCached
= false;
448 fChangeCached
= false;
451 void BindWallet(CWallet
*pwalletIn
)
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());
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())
475 return (!!vfSpent
[nOut
]);
478 int64
GetDebit() const
484 nDebitCached
= pwallet
->GetDebit(*this);
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)
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)
509 if (fUseCache
&& fAvailableCreditCached
)
510 return nAvailableCreditCached
;
513 for (unsigned int i
= 0; i
< vout
.size(); 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;
530 int64
GetChange() const
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
555 if (GetDepthInMainChain() >= 1)
557 if (!IsFromMe()) // using wtx's cached debit
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
];
572 if (ptx
->GetDepthInMainChain() >= 1)
574 if (!pwallet
->IsFromMe(*ptx
))
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
))
587 vWorkQueue
.push_back(mapPrev
[txin
.prevout
.hash
]);
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();
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());
629 printf("%s\n", ToString().c_str());
636 /** Private key that includes an expiration date in case it never gets used. */
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
;
655 if (!(nType
& SER_GETHASH
))
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.
684 vchPubKey
= CPubKey();
689 if (!(nType
& SER_GETHASH
))
691 READWRITE(vchPubKey
);
697 /** Internal transfers.
698 * Database key is acentry<account><counter>.
700 class CAccountingEntry
703 std::string strAccount
;
706 std::string strOtherAccount
;
707 std::string strComment
;
719 strOtherAccount
.clear();
725 if (!(nType
& SER_GETHASH
))
727 // Note: strAccount is serialized as part of the key, not here.
728 READWRITE(nCreditDebit
);
730 READWRITE(strOtherAccount
);
731 READWRITE(strComment
);
735 bool GetWalletFile(CWallet
* pwallet
, std::string
&strWalletFileOut
);