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

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