You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wallet.h 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 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
  7. #include "amount.h"
  8. #include "core/block.h"
  9. #include "core/transaction.h"
  10. #include "crypter.h"
  11. #include "key.h"
  12. #include "keystore.h"
  13. #include "main.h"
  14. #include "ui_interface.h"
  15. #include "wallet_ismine.h"
  16. #include "walletdb.h"
  17. #include <algorithm>
  18. #include <map>
  19. #include <set>
  20. #include <stdexcept>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <utility>
  24. #include <vector>
  25. // Settings
  26. extern CFeeRate payTxFee;
  27. extern unsigned int nTxConfirmTarget;
  28. extern bool bSpendZeroConfChange;
  29. // -paytxfee default
  30. static const CAmount DEFAULT_TRANSACTION_FEE = 0;
  31. // -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
  32. static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
  33. // Largest (in bytes) free transaction we're willing to create
  34. static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
  35. class CAccountingEntry;
  36. class CCoinControl;
  37. class COutput;
  38. class CReserveKey;
  39. class CScript;
  40. class CWalletTx;
  41. /** (client) version numbers for particular wallet features */
  42. enum WalletFeature
  43. {
  44. FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
  45. FEATURE_WALLETCRYPT = 40000, // wallet encryption
  46. FEATURE_COMPRPUBKEY = 60000, // compressed public keys
  47. FEATURE_LATEST = 60000
  48. };
  49. /** A key pool entry */
  50. class CKeyPool
  51. {
  52. public:
  53. int64_t nTime;
  54. CPubKey vchPubKey;
  55. CKeyPool();
  56. CKeyPool(const CPubKey& vchPubKeyIn);
  57. ADD_SERIALIZE_METHODS;
  58. template <typename Stream, typename Operation>
  59. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  60. if (!(nType & SER_GETHASH))
  61. READWRITE(nVersion);
  62. READWRITE(nTime);
  63. READWRITE(vchPubKey);
  64. }
  65. };
  66. /** Address book data */
  67. class CAddressBookData
  68. {
  69. public:
  70. std::string name;
  71. std::string purpose;
  72. CAddressBookData()
  73. {
  74. purpose = "unknown";
  75. }
  76. typedef std::map<std::string, std::string> StringMap;
  77. StringMap destdata;
  78. };
  79. /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
  80. * and provides the ability to create new transactions.
  81. */
  82. class CWallet : public CCryptoKeyStore, public CValidationInterface
  83. {
  84. private:
  85. bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
  86. CWalletDB *pwalletdbEncryption;
  87. // the current wallet version: clients below this version are not able to load the wallet
  88. int nWalletVersion;
  89. // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
  90. int nWalletMaxVersion;
  91. int64_t nNextResend;
  92. int64_t nLastResend;
  93. // Used to keep track of spent outpoints, and
  94. // detect and report conflicts (double-spends or
  95. // mutated transactions where the mutant gets mined).
  96. typedef std::multimap<COutPoint, uint256> TxSpends;
  97. TxSpends mapTxSpends;
  98. void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
  99. void AddToSpends(const uint256& wtxid);
  100. void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
  101. public:
  102. /// Main wallet lock.
  103. /// This lock protects all the fields added by CWallet
  104. /// except for:
  105. /// fFileBacked (immutable after instantiation)
  106. /// strWalletFile (immutable after instantiation)
  107. mutable CCriticalSection cs_wallet;
  108. bool fFileBacked;
  109. std::string strWalletFile;
  110. std::set<int64_t> setKeyPool;
  111. std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
  112. typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
  113. MasterKeyMap mapMasterKeys;
  114. unsigned int nMasterKeyMaxID;
  115. CWallet()
  116. {
  117. SetNull();
  118. }
  119. CWallet(std::string strWalletFileIn)
  120. {
  121. SetNull();
  122. strWalletFile = strWalletFileIn;
  123. fFileBacked = true;
  124. }
  125. ~CWallet()
  126. {
  127. delete pwalletdbEncryption;
  128. pwalletdbEncryption = NULL;
  129. }
  130. void SetNull()
  131. {
  132. nWalletVersion = FEATURE_BASE;
  133. nWalletMaxVersion = FEATURE_BASE;
  134. fFileBacked = false;
  135. nMasterKeyMaxID = 0;
  136. pwalletdbEncryption = NULL;
  137. nOrderPosNext = 0;
  138. nNextResend = 0;
  139. nLastResend = 0;
  140. nTimeFirstKey = 0;
  141. }
  142. std::map<uint256, CWalletTx> mapWallet;
  143. int64_t nOrderPosNext;
  144. std::map<uint256, int> mapRequestCount;
  145. std::map<CTxDestination, CAddressBookData> mapAddressBook;
  146. CPubKey vchDefaultKey;
  147. std::set<COutPoint> setLockedCoins;
  148. int64_t nTimeFirstKey;
  149. const CWalletTx* GetWalletTx(const uint256& hash) const;
  150. // check whether we are allowed to upgrade (or already support) to the named feature
  151. bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
  152. void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL) const;
  153. bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const;
  154. bool IsSpent(const uint256& hash, unsigned int n) const;
  155. bool IsLockedCoin(uint256 hash, unsigned int n) const;
  156. void LockCoin(COutPoint& output);
  157. void UnlockCoin(COutPoint& output);
  158. void UnlockAllCoins();
  159. void ListLockedCoins(std::vector<COutPoint>& vOutpts);
  160. // keystore implementation
  161. // Generate a new key
  162. CPubKey GenerateNewKey();
  163. // Adds a key to the store, and saves it to disk.
  164. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
  165. // Adds a key to the store, without saving it to disk (used by LoadWallet)
  166. bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
  167. // Load metadata (used by LoadWallet)
  168. bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
  169. bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
  170. // Adds an encrypted key to the store, and saves it to disk.
  171. bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
  172. // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
  173. bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
  174. bool AddCScript(const CScript& redeemScript);
  175. bool LoadCScript(const CScript& redeemScript);
  176. /// Adds a destination data tuple to the store, and saves it to disk
  177. bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
  178. /// Erases a destination data tuple in the store and on disk
  179. bool EraseDestData(const CTxDestination &dest, const std::string &key);
  180. /// Adds a destination data tuple to the store, without saving it to disk
  181. bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
  182. /// Look up a destination data tuple in the store, return true if found false otherwise
  183. bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
  184. // Adds a watch-only address to the store, and saves it to disk.
  185. bool AddWatchOnly(const CScript &dest);
  186. bool RemoveWatchOnly(const CScript &dest);
  187. // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
  188. bool LoadWatchOnly(const CScript &dest);
  189. bool Unlock(const SecureString& strWalletPassphrase);
  190. bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
  191. bool EncryptWallet(const SecureString& strWalletPassphrase);
  192. void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
  193. /** Increment the next transaction order id
  194. @return next transaction order id
  195. */
  196. int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
  197. typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
  198. typedef std::multimap<int64_t, TxPair > TxItems;
  199. /** Get the wallet's activity log
  200. @return multimap of ordered transactions and accounting entries
  201. @warning Returned pointers are *only* valid within the scope of passed acentries
  202. */
  203. TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
  204. void MarkDirty();
  205. bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet=false);
  206. void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
  207. bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
  208. void EraseFromWallet(const uint256 &hash);
  209. int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
  210. void ReacceptWalletTransactions();
  211. void ResendWalletTransactions();
  212. CAmount GetBalance() const;
  213. CAmount GetUnconfirmedBalance() const;
  214. CAmount GetImmatureBalance() const;
  215. CAmount GetWatchOnlyBalance() const;
  216. CAmount GetUnconfirmedWatchOnlyBalance() const;
  217. CAmount GetImmatureWatchOnlyBalance() const;
  218. bool CreateTransaction(const std::vector<std::pair<CScript, CAmount> >& vecSend,
  219. CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
  220. bool CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
  221. CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
  222. bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
  223. std::string SendMoney(const CTxDestination &address, CAmount nValue, CWalletTx& wtxNew);
  224. static CFeeRate minTxFee;
  225. static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
  226. bool NewKeyPool();
  227. bool TopUpKeyPool(unsigned int kpSize = 0);
  228. void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
  229. void KeepKey(int64_t nIndex);
  230. void ReturnKey(int64_t nIndex);
  231. bool GetKeyFromPool(CPubKey &key);
  232. int64_t GetOldestKeyPoolTime();
  233. void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
  234. std::set< std::set<CTxDestination> > GetAddressGroupings();
  235. std::map<CTxDestination, CAmount> GetAddressBalances();
  236. std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
  237. isminetype IsMine(const CTxIn& txin) const;
  238. CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
  239. isminetype IsMine(const CTxOut& txout) const
  240. {
  241. return ::IsMine(*this, txout.scriptPubKey);
  242. }
  243. CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const
  244. {
  245. if (!MoneyRange(txout.nValue))
  246. throw std::runtime_error("CWallet::GetCredit() : value out of range");
  247. return ((IsMine(txout) & filter) ? txout.nValue : 0);
  248. }
  249. bool IsChange(const CTxOut& txout) const;
  250. CAmount GetChange(const CTxOut& txout) const
  251. {
  252. if (!MoneyRange(txout.nValue))
  253. throw std::runtime_error("CWallet::GetChange() : value out of range");
  254. return (IsChange(txout) ? txout.nValue : 0);
  255. }
  256. bool IsMine(const CTransaction& tx) const
  257. {
  258. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  259. if (IsMine(txout))
  260. return true;
  261. return false;
  262. }
  263. bool IsFromMe(const CTransaction& tx) const // should probably be renamed to IsRelevantToMe
  264. {
  265. return (GetDebit(tx, ISMINE_ALL) > 0);
  266. }
  267. CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const
  268. {
  269. CAmount nDebit = 0;
  270. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  271. {
  272. nDebit += GetDebit(txin, filter);
  273. if (!MoneyRange(nDebit))
  274. throw std::runtime_error("CWallet::GetDebit() : value out of range");
  275. }
  276. return nDebit;
  277. }
  278. CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const
  279. {
  280. CAmount nCredit = 0;
  281. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  282. {
  283. nCredit += GetCredit(txout, filter);
  284. if (!MoneyRange(nCredit))
  285. throw std::runtime_error("CWallet::GetCredit() : value out of range");
  286. }
  287. return nCredit;
  288. }
  289. CAmount GetChange(const CTransaction& tx) const
  290. {
  291. CAmount nChange = 0;
  292. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  293. {
  294. nChange += GetChange(txout);
  295. if (!MoneyRange(nChange))
  296. throw std::runtime_error("CWallet::GetChange() : value out of range");
  297. }
  298. return nChange;
  299. }
  300. void SetBestChain(const CBlockLocator& loc);
  301. DBErrors LoadWallet(bool& fFirstRunRet);
  302. DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
  303. bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
  304. bool DelAddressBook(const CTxDestination& address);
  305. void UpdatedTransaction(const uint256 &hashTx);
  306. void Inventory(const uint256 &hash)
  307. {
  308. {
  309. LOCK(cs_wallet);
  310. std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
  311. if (mi != mapRequestCount.end())
  312. (*mi).second++;
  313. }
  314. }
  315. unsigned int GetKeyPoolSize()
  316. {
  317. AssertLockHeld(cs_wallet); // setKeyPool
  318. return setKeyPool.size();
  319. }
  320. bool SetDefaultKey(const CPubKey &vchPubKey);
  321. // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
  322. bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
  323. // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
  324. bool SetMaxVersion(int nVersion);
  325. // get the current wallet format (the oldest client version guaranteed to understand this wallet)
  326. int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
  327. // Get wallet transactions that conflict with given transaction (spend same outputs)
  328. std::set<uint256> GetConflicts(const uint256& txid) const;
  329. /** Address book entry changed.
  330. * @note called with lock cs_wallet held.
  331. */
  332. boost::signals2::signal<void (CWallet *wallet, const CTxDestination
  333. &address, const std::string &label, bool isMine,
  334. const std::string &purpose,
  335. ChangeType status)> NotifyAddressBookChanged;
  336. /** Wallet transaction added, removed or updated.
  337. * @note called with lock cs_wallet held.
  338. */
  339. boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
  340. ChangeType status)> NotifyTransactionChanged;
  341. /** Show progress e.g. for rescan */
  342. boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
  343. /** Watch-only address added */
  344. boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
  345. };
  346. /** A key allocated from the key pool. */
  347. class CReserveKey
  348. {
  349. protected:
  350. CWallet* pwallet;
  351. int64_t nIndex;
  352. CPubKey vchPubKey;
  353. public:
  354. CReserveKey(CWallet* pwalletIn)
  355. {
  356. nIndex = -1;
  357. pwallet = pwalletIn;
  358. }
  359. ~CReserveKey()
  360. {
  361. ReturnKey();
  362. }
  363. void ReturnKey();
  364. bool GetReservedKey(CPubKey &pubkey);
  365. void KeepKey();
  366. };
  367. typedef std::map<std::string, std::string> mapValue_t;
  368. static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
  369. {
  370. if (!mapValue.count("n"))
  371. {
  372. nOrderPos = -1; // TODO: calculate elsewhere
  373. return;
  374. }
  375. nOrderPos = atoi64(mapValue["n"].c_str());
  376. }
  377. static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
  378. {
  379. if (nOrderPos == -1)
  380. return;
  381. mapValue["n"] = i64tostr(nOrderPos);
  382. }
  383. struct COutputEntry
  384. {
  385. CTxDestination destination;
  386. CAmount amount;
  387. int vout;
  388. };
  389. /** A transaction with a merkle branch linking it to the block chain. */
  390. class CMerkleTx : public CTransaction
  391. {
  392. private:
  393. int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
  394. public:
  395. uint256 hashBlock;
  396. std::vector<uint256> vMerkleBranch;
  397. int nIndex;
  398. // memory only
  399. mutable bool fMerkleVerified;
  400. CMerkleTx()
  401. {
  402. Init();
  403. }
  404. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  405. {
  406. Init();
  407. }
  408. void Init()
  409. {
  410. hashBlock = 0;
  411. nIndex = -1;
  412. fMerkleVerified = false;
  413. }
  414. ADD_SERIALIZE_METHODS;
  415. template <typename Stream, typename Operation>
  416. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  417. READWRITE(*(CTransaction*)this);
  418. nVersion = this->nVersion;
  419. READWRITE(hashBlock);
  420. READWRITE(vMerkleBranch);
  421. READWRITE(nIndex);
  422. }
  423. int SetMerkleBranch(const CBlock& block);
  424. // Return depth of transaction in blockchain:
  425. // -1 : not in blockchain, and not in memory pool (conflicted transaction)
  426. // 0 : in memory pool, waiting to be included in a block
  427. // >=1 : this many blocks deep in the main chain
  428. int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
  429. int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  430. bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
  431. int GetBlocksToMaturity() const;
  432. bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectInsaneFee=true);
  433. };
  434. /** A transaction with a bunch of additional info that only the owner cares about.
  435. * It includes any unrecorded transactions needed to link it back to the block chain.
  436. */
  437. class CWalletTx : public CMerkleTx
  438. {
  439. private:
  440. const CWallet* pwallet;
  441. public:
  442. mapValue_t mapValue;
  443. std::vector<std::pair<std::string, std::string> > vOrderForm;
  444. unsigned int fTimeReceivedIsTxTime;
  445. unsigned int nTimeReceived; // time received by this node
  446. unsigned int nTimeSmart;
  447. char fFromMe;
  448. std::string strFromAccount;
  449. int64_t nOrderPos; // position in ordered transaction list
  450. // memory only
  451. mutable bool fDebitCached;
  452. mutable bool fCreditCached;
  453. mutable bool fImmatureCreditCached;
  454. mutable bool fAvailableCreditCached;
  455. mutable bool fWatchDebitCached;
  456. mutable bool fWatchCreditCached;
  457. mutable bool fImmatureWatchCreditCached;
  458. mutable bool fAvailableWatchCreditCached;
  459. mutable bool fChangeCached;
  460. mutable CAmount nDebitCached;
  461. mutable CAmount nCreditCached;
  462. mutable CAmount nImmatureCreditCached;
  463. mutable CAmount nAvailableCreditCached;
  464. mutable CAmount nWatchDebitCached;
  465. mutable CAmount nWatchCreditCached;
  466. mutable CAmount nImmatureWatchCreditCached;
  467. mutable CAmount nAvailableWatchCreditCached;
  468. mutable CAmount nChangeCached;
  469. CWalletTx()
  470. {
  471. Init(NULL);
  472. }
  473. CWalletTx(const CWallet* pwalletIn)
  474. {
  475. Init(pwalletIn);
  476. }
  477. CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
  478. {
  479. Init(pwalletIn);
  480. }
  481. CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
  482. {
  483. Init(pwalletIn);
  484. }
  485. void Init(const CWallet* pwalletIn)
  486. {
  487. pwallet = pwalletIn;
  488. mapValue.clear();
  489. vOrderForm.clear();
  490. fTimeReceivedIsTxTime = false;
  491. nTimeReceived = 0;
  492. nTimeSmart = 0;
  493. fFromMe = false;
  494. strFromAccount.clear();
  495. fDebitCached = false;
  496. fCreditCached = false;
  497. fImmatureCreditCached = false;
  498. fAvailableCreditCached = false;
  499. fWatchDebitCached = false;
  500. fWatchCreditCached = false;
  501. fImmatureWatchCreditCached = false;
  502. fAvailableWatchCreditCached = false;
  503. fChangeCached = false;
  504. nDebitCached = 0;
  505. nCreditCached = 0;
  506. nImmatureCreditCached = 0;
  507. nAvailableCreditCached = 0;
  508. nWatchDebitCached = 0;
  509. nWatchCreditCached = 0;
  510. nAvailableWatchCreditCached = 0;
  511. nImmatureWatchCreditCached = 0;
  512. nChangeCached = 0;
  513. nOrderPos = -1;
  514. }
  515. ADD_SERIALIZE_METHODS;
  516. template <typename Stream, typename Operation>
  517. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  518. if (ser_action.ForRead())
  519. Init(NULL);
  520. char fSpent = false;
  521. if (!ser_action.ForRead())
  522. {
  523. mapValue["fromaccount"] = strFromAccount;
  524. WriteOrderPos(nOrderPos, mapValue);
  525. if (nTimeSmart)
  526. mapValue["timesmart"] = strprintf("%u", nTimeSmart);
  527. }
  528. READWRITE(*(CMerkleTx*)this);
  529. std::vector<CMerkleTx> vUnused; // Used to be vtxPrev
  530. READWRITE(vUnused);
  531. READWRITE(mapValue);
  532. READWRITE(vOrderForm);
  533. READWRITE(fTimeReceivedIsTxTime);
  534. READWRITE(nTimeReceived);
  535. READWRITE(fFromMe);
  536. READWRITE(fSpent);
  537. if (ser_action.ForRead())
  538. {
  539. strFromAccount = mapValue["fromaccount"];
  540. ReadOrderPos(nOrderPos, mapValue);
  541. nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
  542. }
  543. mapValue.erase("fromaccount");
  544. mapValue.erase("version");
  545. mapValue.erase("spent");
  546. mapValue.erase("n");
  547. mapValue.erase("timesmart");
  548. }
  549. // make sure balances are recalculated
  550. void MarkDirty()
  551. {
  552. fCreditCached = false;
  553. fAvailableCreditCached = false;
  554. fWatchDebitCached = false;
  555. fWatchCreditCached = false;
  556. fAvailableWatchCreditCached = false;
  557. fImmatureWatchCreditCached = false;
  558. fDebitCached = false;
  559. fChangeCached = false;
  560. }
  561. void BindWallet(CWallet *pwalletIn)
  562. {
  563. pwallet = pwalletIn;
  564. MarkDirty();
  565. }
  566. // filter decides which addresses will count towards the debit
  567. CAmount GetDebit(const isminefilter& filter) const
  568. {
  569. if (vin.empty())
  570. return 0;
  571. CAmount debit = 0;
  572. if(filter & ISMINE_SPENDABLE)
  573. {
  574. if (fDebitCached)
  575. debit += nDebitCached;
  576. else
  577. {
  578. nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
  579. fDebitCached = true;
  580. debit += nDebitCached;
  581. }
  582. }
  583. if(filter & ISMINE_WATCH_ONLY)
  584. {
  585. if(fWatchDebitCached)
  586. debit += nWatchDebitCached;
  587. else
  588. {
  589. nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
  590. fWatchDebitCached = true;
  591. debit += nWatchDebitCached;
  592. }
  593. }
  594. return debit;
  595. }
  596. CAmount GetCredit(const isminefilter& filter) const
  597. {
  598. // Must wait until coinbase is safely deep enough in the chain before valuing it
  599. if (IsCoinBase() && GetBlocksToMaturity() > 0)
  600. return 0;
  601. int64_t credit = 0;
  602. if (filter & ISMINE_SPENDABLE)
  603. {
  604. // GetBalance can assume transactions in mapWallet won't change
  605. if (fCreditCached)
  606. credit += nCreditCached;
  607. else
  608. {
  609. nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
  610. fCreditCached = true;
  611. credit += nCreditCached;
  612. }
  613. }
  614. if (filter & ISMINE_WATCH_ONLY)
  615. {
  616. if (fWatchCreditCached)
  617. credit += nWatchCreditCached;
  618. else
  619. {
  620. nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
  621. fWatchCreditCached = true;
  622. credit += nWatchCreditCached;
  623. }
  624. }
  625. return credit;
  626. }
  627. CAmount GetImmatureCredit(bool fUseCache=true) const
  628. {
  629. if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
  630. {
  631. if (fUseCache && fImmatureCreditCached)
  632. return nImmatureCreditCached;
  633. nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
  634. fImmatureCreditCached = true;
  635. return nImmatureCreditCached;
  636. }
  637. return 0;
  638. }
  639. CAmount GetAvailableCredit(bool fUseCache=true) const
  640. {
  641. if (pwallet == 0)
  642. return 0;
  643. // Must wait until coinbase is safely deep enough in the chain before valuing it
  644. if (IsCoinBase() && GetBlocksToMaturity() > 0)
  645. return 0;
  646. if (fUseCache && fAvailableCreditCached)
  647. return nAvailableCreditCached;
  648. CAmount nCredit = 0;
  649. uint256 hashTx = GetHash();
  650. for (unsigned int i = 0; i < vout.size(); i++)
  651. {
  652. if (!pwallet->IsSpent(hashTx, i))
  653. {
  654. const CTxOut &txout = vout[i];
  655. nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
  656. if (!MoneyRange(nCredit))
  657. throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
  658. }
  659. }
  660. nAvailableCreditCached = nCredit;
  661. fAvailableCreditCached = true;
  662. return nCredit;
  663. }
  664. CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const
  665. {
  666. if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
  667. {
  668. if (fUseCache && fImmatureWatchCreditCached)
  669. return nImmatureWatchCreditCached;
  670. nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
  671. fImmatureWatchCreditCached = true;
  672. return nImmatureWatchCreditCached;
  673. }
  674. return 0;
  675. }
  676. CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const
  677. {
  678. if (pwallet == 0)
  679. return 0;
  680. // Must wait until coinbase is safely deep enough in the chain before valuing it
  681. if (IsCoinBase() && GetBlocksToMaturity() > 0)
  682. return 0;
  683. if (fUseCache && fAvailableWatchCreditCached)
  684. return nAvailableWatchCreditCached;
  685. CAmount nCredit = 0;
  686. for (unsigned int i = 0; i < vout.size(); i++)
  687. {
  688. if (!pwallet->IsSpent(GetHash(), i))
  689. {
  690. const CTxOut &txout = vout[i];
  691. nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
  692. if (!MoneyRange(nCredit))
  693. throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
  694. }
  695. }
  696. nAvailableWatchCreditCached = nCredit;
  697. fAvailableWatchCreditCached = true;
  698. return nCredit;
  699. }
  700. CAmount GetChange() const
  701. {
  702. if (fChangeCached)
  703. return nChangeCached;
  704. nChangeCached = pwallet->GetChange(*this);
  705. fChangeCached = true;
  706. return nChangeCached;
  707. }
  708. void GetAmounts(std::list<COutputEntry>& listReceived,
  709. std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
  710. void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
  711. CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
  712. bool IsFromMe(const isminefilter& filter) const
  713. {
  714. return (GetDebit(filter) > 0);
  715. }
  716. bool IsTrusted() const
  717. {
  718. // Quick answer in most cases
  719. if (!IsFinalTx(*this))
  720. return false;
  721. int nDepth = GetDepthInMainChain();
  722. if (nDepth >= 1)
  723. return true;
  724. if (nDepth < 0)
  725. return false;
  726. if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
  727. return false;
  728. // Trusted if all inputs are from us and are in the mempool:
  729. BOOST_FOREACH(const CTxIn& txin, vin)
  730. {
  731. // Transactions not sent by us: not trusted
  732. const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
  733. if (parent == NULL)
  734. return false;
  735. const CTxOut& parentOut = parent->vout[txin.prevout.n];
  736. if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
  737. return false;
  738. }
  739. return true;
  740. }
  741. bool WriteToDisk();
  742. int64_t GetTxTime() const;
  743. int GetRequestCount() const;
  744. void RelayWalletTransaction();
  745. std::set<uint256> GetConflicts() const;
  746. };
  747. class COutput
  748. {
  749. public:
  750. const CWalletTx *tx;
  751. int i;
  752. int nDepth;
  753. bool fSpendable;
  754. COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
  755. {
  756. tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
  757. }
  758. std::string ToString() const;
  759. };
  760. /** Private key that includes an expiration date in case it never gets used. */
  761. class CWalletKey
  762. {
  763. public:
  764. CPrivKey vchPrivKey;
  765. int64_t nTimeCreated;
  766. int64_t nTimeExpires;
  767. std::string strComment;
  768. //// todo: add something to note what created it (user, getnewaddress, change)
  769. //// maybe should have a map<string, string> property map
  770. CWalletKey(int64_t nExpires=0);
  771. ADD_SERIALIZE_METHODS;
  772. template <typename Stream, typename Operation>
  773. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  774. if (!(nType & SER_GETHASH))
  775. READWRITE(nVersion);
  776. READWRITE(vchPrivKey);
  777. READWRITE(nTimeCreated);
  778. READWRITE(nTimeExpires);
  779. READWRITE(LIMITED_STRING(strComment, 65536));
  780. }
  781. };
  782. /** Account information.
  783. * Stored in wallet with key "acc"+string account name.
  784. */
  785. class CAccount
  786. {
  787. public:
  788. CPubKey vchPubKey;
  789. CAccount()
  790. {
  791. SetNull();
  792. }
  793. void SetNull()
  794. {
  795. vchPubKey = CPubKey();
  796. }
  797. ADD_SERIALIZE_METHODS;
  798. template <typename Stream, typename Operation>
  799. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  800. if (!(nType & SER_GETHASH))
  801. READWRITE(nVersion);
  802. READWRITE(vchPubKey);
  803. }
  804. };
  805. /** Internal transfers.
  806. * Database key is acentry<account><counter>.
  807. */
  808. class CAccountingEntry
  809. {
  810. public:
  811. std::string strAccount;
  812. CAmount nCreditDebit;
  813. int64_t nTime;
  814. std::string strOtherAccount;
  815. std::string strComment;
  816. mapValue_t mapValue;
  817. int64_t nOrderPos; // position in ordered transaction list
  818. uint64_t nEntryNo;
  819. CAccountingEntry()
  820. {
  821. SetNull();
  822. }
  823. void SetNull()
  824. {
  825. nCreditDebit = 0;
  826. nTime = 0;
  827. strAccount.clear();
  828. strOtherAccount.clear();
  829. strComment.clear();
  830. nOrderPos = -1;
  831. nEntryNo = 0;
  832. }
  833. ADD_SERIALIZE_METHODS;
  834. template <typename Stream, typename Operation>
  835. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  836. if (!(nType & SER_GETHASH))
  837. READWRITE(nVersion);
  838. // Note: strAccount is serialized as part of the key, not here.
  839. READWRITE(nCreditDebit);
  840. READWRITE(nTime);
  841. READWRITE(LIMITED_STRING(strOtherAccount, 65536));
  842. if (!ser_action.ForRead())
  843. {
  844. WriteOrderPos(nOrderPos, mapValue);
  845. if (!(mapValue.empty() && _ssExtra.empty()))
  846. {
  847. CDataStream ss(nType, nVersion);
  848. ss.insert(ss.begin(), '\0');
  849. ss << mapValue;
  850. ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
  851. strComment.append(ss.str());
  852. }
  853. }
  854. READWRITE(LIMITED_STRING(strComment, 65536));
  855. size_t nSepPos = strComment.find("\0", 0, 1);
  856. if (ser_action.ForRead())
  857. {
  858. mapValue.clear();
  859. if (std::string::npos != nSepPos)
  860. {
  861. CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
  862. ss >> mapValue;
  863. _ssExtra = std::vector<char>(ss.begin(), ss.end());
  864. }
  865. ReadOrderPos(nOrderPos, mapValue);
  866. }
  867. if (std::string::npos != nSepPos)
  868. strComment.erase(nSepPos);
  869. mapValue.erase("n");
  870. }
  871. private:
  872. std::vector<char> _ssExtra;
  873. };
  874. #endif // BITCOIN_WALLET_H