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

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