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 31KB

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