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

Add wallet privkey encryption. This commit adds support for ckeys, or enCrypted private keys, to the wallet. All keys are stored in memory in their encrypted form and thus the passphrase is required from the user to spend coins, or to create new addresses. Keys are encrypted with AES-256-CBC using OpenSSL's EVP library. The key is calculated via EVP_BytesToKey using SHA512 with (by default) 25000 rounds and a random salt. By default, the user's wallet remains unencrypted until they call the RPC command encryptwallet <passphrase> or, from the GUI menu, Options-> Encrypt Wallet. When the user is attempting to call RPC functions which require the password to unlock the wallet, an error will be returned unless they call walletpassphrase <passphrase> <time to keep key in memory> first. A keypoolrefill command has been added which tops up the users keypool (requiring the passphrase via walletpassphrase first). keypoolsize has been added to the output of getinfo to show the user the number of keys left before they need to specify their passphrase (and call keypoolrefill). Note that walletpassphrase will automatically fill keypool in a separate thread which it spawns when the passphrase is set. This could cause some delays in other threads waiting for locks on the wallet passphrase, including one which could cause the passphrase to be stored longer than expected, however it will not allow the passphrase to be used longer than expected as ThreadCleanWalletPassphrase will attempt to get a lock on the key as soon as the specified lock time has arrived. When the keypool runs out (and wallet is locked) GetOrReuseKeyFromPool returns vchDefaultKey, meaning miners may start to generate many blocks to vchDefaultKey instead of a new key each time. A walletpassphrasechange <oldpassphrase> <newpassphrase> has been added to allow the user to change their password via RPC. Whenever keying material (unencrypted private keys, the user's passphrase, the wallet's AES key) is stored unencrypted in memory, any reasonable attempt is made to mlock/VirtualLock that memory before storing the keying material. This is not true in several (commented) cases where mlock/VirtualLocking the memory is not possible. Although encryption of private keys in memory can be very useful on desktop systems (as some small amount of protection against stupid viruses), on an RPC server, the password is entered fairly insecurely. Thus, the only main advantage encryption has for RPC servers is for RPC servers that do not spend coins, except in rare cases, eg. a webserver of a merchant which only receives payment except for cases of manual intervention. Thanks to jgarzik for the original patch and sipa, gmaxwell and many others for all their input. Conflicts: src/wallet.cpp
9 years ago
Add wallet privkey encryption. This commit adds support for ckeys, or enCrypted private keys, to the wallet. All keys are stored in memory in their encrypted form and thus the passphrase is required from the user to spend coins, or to create new addresses. Keys are encrypted with AES-256-CBC using OpenSSL's EVP library. The key is calculated via EVP_BytesToKey using SHA512 with (by default) 25000 rounds and a random salt. By default, the user's wallet remains unencrypted until they call the RPC command encryptwallet <passphrase> or, from the GUI menu, Options-> Encrypt Wallet. When the user is attempting to call RPC functions which require the password to unlock the wallet, an error will be returned unless they call walletpassphrase <passphrase> <time to keep key in memory> first. A keypoolrefill command has been added which tops up the users keypool (requiring the passphrase via walletpassphrase first). keypoolsize has been added to the output of getinfo to show the user the number of keys left before they need to specify their passphrase (and call keypoolrefill). Note that walletpassphrase will automatically fill keypool in a separate thread which it spawns when the passphrase is set. This could cause some delays in other threads waiting for locks on the wallet passphrase, including one which could cause the passphrase to be stored longer than expected, however it will not allow the passphrase to be used longer than expected as ThreadCleanWalletPassphrase will attempt to get a lock on the key as soon as the specified lock time has arrived. When the keypool runs out (and wallet is locked) GetOrReuseKeyFromPool returns vchDefaultKey, meaning miners may start to generate many blocks to vchDefaultKey instead of a new key each time. A walletpassphrasechange <oldpassphrase> <newpassphrase> has been added to allow the user to change their password via RPC. Whenever keying material (unencrypted private keys, the user's passphrase, the wallet's AES key) is stored unencrypted in memory, any reasonable attempt is made to mlock/VirtualLock that memory before storing the keying material. This is not true in several (commented) cases where mlock/VirtualLocking the memory is not possible. Although encryption of private keys in memory can be very useful on desktop systems (as some small amount of protection against stupid viruses), on an RPC server, the password is entered fairly insecurely. Thus, the only main advantage encryption has for RPC servers is for RPC servers that do not spend coins, except in rare cases, eg. a webserver of a merchant which only receives payment except for cases of manual intervention. Thanks to jgarzik for the original patch and sipa, gmaxwell and many others for all their input. Conflicts: src/wallet.cpp
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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 "key.h"
  9. #include "keystore.h"
  10. #include "primitives/block.h"
  11. #include "primitives/transaction.h"
  12. #include "tinyformat.h"
  13. #include "ui_interface.h"
  14. #include "utilstrencodings.h"
  15. #include "validationinterface.h"
  16. #include "wallet/crypter.h"
  17. #include "wallet/wallet_ismine.h"
  18. #include "wallet/walletdb.h"
  19. #include <algorithm>
  20. #include <map>
  21. #include <set>
  22. #include <stdexcept>
  23. #include <stdint.h>
  24. #include <string>
  25. #include <utility>
  26. #include <vector>
  27. /**
  28. * Settings
  29. */
  30. extern CFeeRate payTxFee;
  31. extern CAmount maxTxFee;
  32. extern unsigned int nTxConfirmTarget;
  33. extern bool bSpendZeroConfChange;
  34. extern bool fSendFreeTransactions;
  35. extern bool fPayAtLeastCustomFee;
  36. //! -paytxfee default
  37. static const CAmount DEFAULT_TRANSACTION_FEE = 0;
  38. //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
  39. static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
  40. //! -maxtxfee default
  41. static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN;
  42. //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
  43. static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
  44. //! Largest (in bytes) free transaction we're willing to create
  45. static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
  46. class CAccountingEntry;
  47. class CBlockIndex;
  48. class CCoinControl;
  49. class COutput;
  50. class CReserveKey;
  51. class CScript;
  52. class CTxMemPool;
  53. class CWalletTx;
  54. /** (client) version numbers for particular wallet features */
  55. enum WalletFeature
  56. {
  57. FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
  58. FEATURE_WALLETCRYPT = 40000, // wallet encryption
  59. FEATURE_COMPRPUBKEY = 60000, // compressed public keys
  60. FEATURE_LATEST = 60000
  61. };
  62. /** A key pool entry */
  63. class CKeyPool
  64. {
  65. public:
  66. int64_t nTime;
  67. CPubKey vchPubKey;
  68. CKeyPool();
  69. CKeyPool(const CPubKey& vchPubKeyIn);
  70. ADD_SERIALIZE_METHODS;
  71. template <typename Stream, typename Operation>
  72. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  73. if (!(nType & SER_GETHASH))
  74. READWRITE(nVersion);
  75. READWRITE(nTime);
  76. READWRITE(vchPubKey);
  77. }
  78. };
  79. /** Address book data */
  80. class CAddressBookData
  81. {
  82. public:
  83. std::string name;
  84. std::string purpose;
  85. CAddressBookData()
  86. {
  87. purpose = "unknown";
  88. }
  89. typedef std::map<std::string, std::string> StringMap;
  90. StringMap destdata;
  91. };
  92. struct CRecipient
  93. {
  94. CScript scriptPubKey;
  95. CAmount nAmount;
  96. bool fSubtractFeeFromAmount;
  97. };
  98. typedef std::map<std::string, std::string> mapValue_t;
  99. static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
  100. {
  101. if (!mapValue.count("n"))
  102. {
  103. nOrderPos = -1; // TODO: calculate elsewhere
  104. return;
  105. }
  106. nOrderPos = atoi64(mapValue["n"].c_str());
  107. }
  108. static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
  109. {
  110. if (nOrderPos == -1)
  111. return;
  112. mapValue["n"] = i64tostr(nOrderPos);
  113. }
  114. struct COutputEntry
  115. {
  116. CTxDestination destination;
  117. CAmount amount;
  118. int vout;
  119. };
  120. /** A transaction with a merkle branch linking it to the block chain. */
  121. class CMerkleTx : public CTransaction
  122. {
  123. private:
  124. int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
  125. public:
  126. uint256 hashBlock;
  127. std::vector<uint256> vMerkleBranch;
  128. int nIndex;
  129. // memory only
  130. mutable bool fMerkleVerified;
  131. CMerkleTx()
  132. {
  133. Init();
  134. }
  135. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  136. {
  137. Init();
  138. }
  139. void Init()
  140. {
  141. hashBlock = uint256();
  142. nIndex = -1;
  143. fMerkleVerified = false;
  144. }
  145. ADD_SERIALIZE_METHODS;
  146. template <typename Stream, typename Operation>
  147. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  148. READWRITE(*(CTransaction*)this);
  149. nVersion = this->nVersion;
  150. READWRITE(hashBlock);
  151. READWRITE(vMerkleBranch);
  152. READWRITE(nIndex);
  153. }
  154. int SetMerkleBranch(const CBlock& block);
  155. /**
  156. * Return depth of transaction in blockchain:
  157. * -1 : not in blockchain, and not in memory pool (conflicted transaction)
  158. * 0 : in memory pool, waiting to be included in a block
  159. * >=1 : this many blocks deep in the main chain
  160. */
  161. int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
  162. int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  163. bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
  164. int GetBlocksToMaturity() const;
  165. bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
  166. };
  167. /**
  168. * A transaction with a bunch of additional info that only the owner cares about.
  169. * It includes any unrecorded transactions needed to link it back to the block chain.
  170. */
  171. class CWalletTx : public CMerkleTx
  172. {
  173. private:
  174. const CWallet* pwallet;
  175. public:
  176. mapValue_t mapValue;
  177. std::vector<std::pair<std::string, std::string> > vOrderForm;
  178. unsigned int fTimeReceivedIsTxTime;
  179. unsigned int nTimeReceived; //! time received by this node
  180. unsigned int nTimeSmart;
  181. char fFromMe;
  182. std::string strFromAccount;
  183. int64_t nOrderPos; //! position in ordered transaction list
  184. // memory only
  185. mutable bool fDebitCached;
  186. mutable bool fCreditCached;
  187. mutable bool fImmatureCreditCached;
  188. mutable bool fAvailableCreditCached;
  189. mutable bool fWatchDebitCached;
  190. mutable bool fWatchCreditCached;
  191. mutable bool fImmatureWatchCreditCached;
  192. mutable bool fAvailableWatchCreditCached;
  193. mutable bool fChangeCached;
  194. mutable CAmount nDebitCached;
  195. mutable CAmount nCreditCached;
  196. mutable CAmount nImmatureCreditCached;
  197. mutable CAmount nAvailableCreditCached;
  198. mutable CAmount nWatchDebitCached;
  199. mutable CAmount nWatchCreditCached;
  200. mutable CAmount nImmatureWatchCreditCached;
  201. mutable CAmount nAvailableWatchCreditCached;
  202. mutable CAmount nChangeCached;
  203. CWalletTx()
  204. {
  205. Init(NULL);
  206. }
  207. CWalletTx(const CWallet* pwalletIn)
  208. {
  209. Init(pwalletIn);
  210. }
  211. CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
  212. {
  213. Init(pwalletIn);
  214. }
  215. CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
  216. {
  217. Init(pwalletIn);
  218. }
  219. void Init(const CWallet* pwalletIn)
  220. {
  221. pwallet = pwalletIn;
  222. mapValue.clear();
  223. vOrderForm.clear();
  224. fTimeReceivedIsTxTime = false;
  225. nTimeReceived = 0;
  226. nTimeSmart = 0;
  227. fFromMe = false;
  228. strFromAccount.clear();
  229. fDebitCached = false;
  230. fCreditCached = false;
  231. fImmatureCreditCached = false;
  232. fAvailableCreditCached = false;
  233. fWatchDebitCached = false;
  234. fWatchCreditCached = false;
  235. fImmatureWatchCreditCached = false;
  236. fAvailableWatchCreditCached = false;
  237. fChangeCached = false;
  238. nDebitCached = 0;
  239. nCreditCached = 0;
  240. nImmatureCreditCached = 0;
  241. nAvailableCreditCached = 0;
  242. nWatchDebitCached = 0;
  243. nWatchCreditCached = 0;
  244. nAvailableWatchCreditCached = 0;
  245. nImmatureWatchCreditCached = 0;
  246. nChangeCached = 0;
  247. nOrderPos = -1;
  248. }
  249. ADD_SERIALIZE_METHODS;
  250. template <typename Stream, typename Operation>
  251. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  252. if (ser_action.ForRead())
  253. Init(NULL);
  254. char fSpent = false;
  255. if (!ser_action.ForRead())
  256. {
  257. mapValue["fromaccount"] = strFromAccount;
  258. WriteOrderPos(nOrderPos, mapValue);
  259. if (nTimeSmart)
  260. mapValue["timesmart"] = strprintf("%u", nTimeSmart);
  261. }
  262. READWRITE(*(CMerkleTx*)this);
  263. std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
  264. READWRITE(vUnused);
  265. READWRITE(mapValue);
  266. READWRITE(vOrderForm);
  267. READWRITE(fTimeReceivedIsTxTime);
  268. READWRITE(nTimeReceived);
  269. READWRITE(fFromMe);
  270. READWRITE(fSpent);
  271. if (ser_action.ForRead())
  272. {
  273. strFromAccount = mapValue["fromaccount"];
  274. ReadOrderPos(nOrderPos, mapValue);
  275. nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
  276. }
  277. mapValue.erase("fromaccount");
  278. mapValue.erase("version");
  279. mapValue.erase("spent");
  280. mapValue.erase("n");
  281. mapValue.erase("timesmart");
  282. }
  283. //! make sure balances are recalculated
  284. void MarkDirty()
  285. {
  286. fCreditCached = false;
  287. fAvailableCreditCached = false;
  288. fWatchDebitCached = false;
  289. fWatchCreditCached = false;
  290. fAvailableWatchCreditCached = false;
  291. fImmatureWatchCreditCached = false;
  292. fDebitCached = false;
  293. fChangeCached = false;
  294. }
  295. void BindWallet(CWallet *pwalletIn)
  296. {
  297. pwallet = pwalletIn;
  298. MarkDirty();
  299. }
  300. //! filter decides which addresses will count towards the debit
  301. CAmount GetDebit(const isminefilter& filter) const;
  302. CAmount GetCredit(const isminefilter& filter) const;
  303. CAmount GetImmatureCredit(bool fUseCache=true) const;
  304. CAmount GetAvailableCredit(bool fUseCache=true) const;
  305. CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
  306. CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
  307. CAmount GetChange() const;
  308. void GetAmounts(std::list<COutputEntry>& listReceived,
  309. std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
  310. void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
  311. CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
  312. bool IsFromMe(const isminefilter& filter) const
  313. {
  314. return (GetDebit(filter) > 0);
  315. }
  316. bool IsTrusted() const;
  317. bool WriteToDisk(CWalletDB *pwalletdb);
  318. int64_t GetTxTime() const;
  319. int GetRequestCount() const;
  320. bool RelayWalletTransaction();
  321. std::set<uint256> GetConflicts() const;
  322. };
  323. class COutput
  324. {
  325. public:
  326. const CWalletTx *tx;
  327. int i;
  328. int nDepth;
  329. bool fSpendable;
  330. COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
  331. {
  332. tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
  333. }
  334. std::string ToString() const;
  335. };
  336. /** Private key that includes an expiration date in case it never gets used. */
  337. class CWalletKey
  338. {
  339. public:
  340. CPrivKey vchPrivKey;
  341. int64_t nTimeCreated;
  342. int64_t nTimeExpires;
  343. std::string strComment;
  344. //! todo: add something to note what created it (user, getnewaddress, change)
  345. //! maybe should have a map<string, string> property map
  346. CWalletKey(int64_t nExpires=0);
  347. ADD_SERIALIZE_METHODS;
  348. template <typename Stream, typename Operation>
  349. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  350. if (!(nType & SER_GETHASH))
  351. READWRITE(nVersion);
  352. READWRITE(vchPrivKey);
  353. READWRITE(nTimeCreated);
  354. READWRITE(nTimeExpires);
  355. READWRITE(LIMITED_STRING(strComment, 65536));
  356. }
  357. };
  358. /**
  359. * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
  360. * and provides the ability to create new transactions.
  361. */
  362. class CWallet : public CCryptoKeyStore, public CValidationInterface
  363. {
  364. private:
  365. bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
  366. CWalletDB *pwalletdbEncryption;
  367. //! the current wallet version: clients below this version are not able to load the wallet
  368. int nWalletVersion;
  369. //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
  370. int nWalletMaxVersion;
  371. int64_t nNextResend;
  372. int64_t nLastResend;
  373. bool fBroadcastTransactions;
  374. /**
  375. * Used to keep track of spent outpoints, and
  376. * detect and report conflicts (double-spends or
  377. * mutated transactions where the mutant gets mined).
  378. */
  379. typedef std::multimap<COutPoint, uint256> TxSpends;
  380. TxSpends mapTxSpends;
  381. void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
  382. void AddToSpends(const uint256& wtxid);
  383. void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
  384. public:
  385. /*
  386. * Main wallet lock.
  387. * This lock protects all the fields added by CWallet
  388. * except for:
  389. * fFileBacked (immutable after instantiation)
  390. * strWalletFile (immutable after instantiation)
  391. */
  392. mutable CCriticalSection cs_wallet;
  393. bool fFileBacked;
  394. std::string strWalletFile;
  395. std::set<int64_t> setKeyPool;
  396. std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
  397. typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
  398. MasterKeyMap mapMasterKeys;
  399. unsigned int nMasterKeyMaxID;
  400. CWallet()
  401. {
  402. SetNull();
  403. }
  404. CWallet(std::string strWalletFileIn)
  405. {
  406. SetNull();
  407. strWalletFile = strWalletFileIn;
  408. fFileBacked = true;
  409. }
  410. ~CWallet()
  411. {
  412. delete pwalletdbEncryption;
  413. pwalletdbEncryption = NULL;
  414. }
  415. void SetNull()
  416. {
  417. nWalletVersion = FEATURE_BASE;
  418. nWalletMaxVersion = FEATURE_BASE;
  419. fFileBacked = false;
  420. nMasterKeyMaxID = 0;
  421. pwalletdbEncryption = NULL;
  422. nOrderPosNext = 0;
  423. nNextResend = 0;
  424. nLastResend = 0;
  425. nTimeFirstKey = 0;
  426. fBroadcastTransactions = false;
  427. }
  428. std::map<uint256, CWalletTx> mapWallet;
  429. int64_t nOrderPosNext;
  430. std::map<uint256, int> mapRequestCount;
  431. std::map<CTxDestination, CAddressBookData> mapAddressBook;
  432. CPubKey vchDefaultKey;
  433. std::set<COutPoint> setLockedCoins;
  434. int64_t nTimeFirstKey;
  435. const CWalletTx* GetWalletTx(const uint256& hash) const;
  436. //! check whether we are allowed to upgrade (or already support) to the named feature
  437. bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
  438. void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL) const;
  439. 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;
  440. bool IsSpent(const uint256& hash, unsigned int n) const;
  441. bool IsLockedCoin(uint256 hash, unsigned int n) const;
  442. void LockCoin(COutPoint& output);
  443. void UnlockCoin(COutPoint& output);
  444. void UnlockAllCoins();
  445. void ListLockedCoins(std::vector<COutPoint>& vOutpts);
  446. /**
  447. * keystore implementation
  448. * Generate a new key
  449. */
  450. CPubKey GenerateNewKey();
  451. //! Adds a key to the store, and saves it to disk.
  452. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
  453. //! Adds a key to the store, without saving it to disk (used by LoadWallet)
  454. bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
  455. //! Load metadata (used by LoadWallet)
  456. bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
  457. bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
  458. //! Adds an encrypted key to the store, and saves it to disk.
  459. bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
  460. //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
  461. bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
  462. bool AddCScript(const CScript& redeemScript);
  463. bool LoadCScript(const CScript& redeemScript);
  464. //! Adds a destination data tuple to the store, and saves it to disk
  465. bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
  466. //! Erases a destination data tuple in the store and on disk
  467. bool EraseDestData(const CTxDestination &dest, const std::string &key);
  468. //! Adds a destination data tuple to the store, without saving it to disk
  469. bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
  470. //! Look up a destination data tuple in the store, return true if found false otherwise
  471. bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
  472. //! Adds a watch-only address to the store, and saves it to disk.
  473. bool AddWatchOnly(const CScript &dest);
  474. bool RemoveWatchOnly(const CScript &dest);
  475. //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
  476. bool LoadWatchOnly(const CScript &dest);
  477. bool Unlock(const SecureString& strWalletPassphrase);
  478. bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
  479. bool EncryptWallet(const SecureString& strWalletPassphrase);
  480. void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
  481. /**
  482. * Increment the next transaction order id
  483. * @return next transaction order id
  484. */
  485. int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
  486. typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
  487. typedef std::multimap<int64_t, TxPair > TxItems;
  488. /**
  489. * Get the wallet's activity log
  490. * @return multimap of ordered transactions and accounting entries
  491. * @warning Returned pointers are *only* valid within the scope of passed acentries
  492. */
  493. TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
  494. void MarkDirty();
  495. bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
  496. void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
  497. bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
  498. void EraseFromWallet(const uint256 &hash);
  499. int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
  500. void ReacceptWalletTransactions();
  501. void ResendWalletTransactions(int64_t nBestBlockTime);
  502. std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
  503. CAmount GetBalance() const;
  504. CAmount GetUnconfirmedBalance() const;
  505. CAmount GetImmatureBalance() const;
  506. CAmount GetWatchOnlyBalance() const;
  507. CAmount GetUnconfirmedWatchOnlyBalance() const;
  508. CAmount GetImmatureWatchOnlyBalance() const;
  509. bool CreateTransaction(const std::vector<CRecipient>& vecSend,
  510. CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
  511. bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
  512. static CFeeRate minTxFee;
  513. static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
  514. bool NewKeyPool();
  515. bool TopUpKeyPool(unsigned int kpSize = 0);
  516. void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
  517. void KeepKey(int64_t nIndex);
  518. void ReturnKey(int64_t nIndex);
  519. bool GetKeyFromPool(CPubKey &key);
  520. int64_t GetOldestKeyPoolTime();
  521. void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
  522. std::set< std::set<CTxDestination> > GetAddressGroupings();
  523. std::map<CTxDestination, CAmount> GetAddressBalances();
  524. std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
  525. isminetype IsMine(const CTxIn& txin) const;
  526. CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
  527. isminetype IsMine(const CTxOut& txout) const;
  528. CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
  529. bool IsChange(const CTxOut& txout) const;
  530. CAmount GetChange(const CTxOut& txout) const;
  531. bool IsMine(const CTransaction& tx) const;
  532. /** should probably be renamed to IsRelevantToMe */
  533. bool IsFromMe(const CTransaction& tx) const;
  534. CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
  535. CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
  536. CAmount GetChange(const CTransaction& tx) const;
  537. void SetBestChain(const CBlockLocator& loc);
  538. DBErrors LoadWallet(bool& fFirstRunRet);
  539. DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
  540. bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
  541. bool DelAddressBook(const CTxDestination& address);
  542. void UpdatedTransaction(const uint256 &hashTx);
  543. void Inventory(const uint256 &hash)
  544. {
  545. {
  546. LOCK(cs_wallet);
  547. std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
  548. if (mi != mapRequestCount.end())
  549. (*mi).second++;
  550. }
  551. }
  552. unsigned int GetKeyPoolSize()
  553. {
  554. AssertLockHeld(cs_wallet); // setKeyPool
  555. return setKeyPool.size();
  556. }
  557. bool SetDefaultKey(const CPubKey &vchPubKey);
  558. //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
  559. bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
  560. //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
  561. bool SetMaxVersion(int nVersion);
  562. //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
  563. int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
  564. //! Get wallet transactions that conflict with given transaction (spend same outputs)
  565. std::set<uint256> GetConflicts(const uint256& txid) const;
  566. //! Flush wallet (bitdb flush)
  567. void Flush(bool shutdown=false);
  568. //! Verify the wallet database and perform salvage if required
  569. static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
  570. /**
  571. * Address book entry changed.
  572. * @note called with lock cs_wallet held.
  573. */
  574. boost::signals2::signal<void (CWallet *wallet, const CTxDestination
  575. &address, const std::string &label, bool isMine,
  576. const std::string &purpose,
  577. ChangeType status)> NotifyAddressBookChanged;
  578. /**
  579. * Wallet transaction added, removed or updated.
  580. * @note called with lock cs_wallet held.
  581. */
  582. boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
  583. ChangeType status)> NotifyTransactionChanged;
  584. /** Show progress e.g. for rescan */
  585. boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
  586. /** Watch-only address added */
  587. boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
  588. /** Inquire whether this wallet broadcasts transactions. */
  589. bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
  590. /** Set whether this wallet broadcasts transactions. */
  591. void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
  592. };
  593. /** A key allocated from the key pool. */
  594. class CReserveKey
  595. {
  596. protected:
  597. CWallet* pwallet;
  598. int64_t nIndex;
  599. CPubKey vchPubKey;
  600. public:
  601. CReserveKey(CWallet* pwalletIn)
  602. {
  603. nIndex = -1;
  604. pwallet = pwalletIn;
  605. }
  606. ~CReserveKey()
  607. {
  608. ReturnKey();
  609. }
  610. void ReturnKey();
  611. bool GetReservedKey(CPubKey &pubkey);
  612. void KeepKey();
  613. };
  614. /**
  615. * Account information.
  616. * Stored in wallet with key "acc"+string account name.
  617. */
  618. class CAccount
  619. {
  620. public:
  621. CPubKey vchPubKey;
  622. CAccount()
  623. {
  624. SetNull();
  625. }
  626. void SetNull()
  627. {
  628. vchPubKey = CPubKey();
  629. }
  630. ADD_SERIALIZE_METHODS;
  631. template <typename Stream, typename Operation>
  632. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  633. if (!(nType & SER_GETHASH))
  634. READWRITE(nVersion);
  635. READWRITE(vchPubKey);
  636. }
  637. };
  638. /**
  639. * Internal transfers.
  640. * Database key is acentry<account><counter>.
  641. */
  642. class CAccountingEntry
  643. {
  644. public:
  645. std::string strAccount;
  646. CAmount nCreditDebit;
  647. int64_t nTime;
  648. std::string strOtherAccount;
  649. std::string strComment;
  650. mapValue_t mapValue;
  651. int64_t nOrderPos; //! position in ordered transaction list
  652. uint64_t nEntryNo;
  653. CAccountingEntry()
  654. {
  655. SetNull();
  656. }
  657. void SetNull()
  658. {
  659. nCreditDebit = 0;
  660. nTime = 0;
  661. strAccount.clear();
  662. strOtherAccount.clear();
  663. strComment.clear();
  664. nOrderPos = -1;
  665. nEntryNo = 0;
  666. }
  667. ADD_SERIALIZE_METHODS;
  668. template <typename Stream, typename Operation>
  669. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  670. if (!(nType & SER_GETHASH))
  671. READWRITE(nVersion);
  672. //! Note: strAccount is serialized as part of the key, not here.
  673. READWRITE(nCreditDebit);
  674. READWRITE(nTime);
  675. READWRITE(LIMITED_STRING(strOtherAccount, 65536));
  676. if (!ser_action.ForRead())
  677. {
  678. WriteOrderPos(nOrderPos, mapValue);
  679. if (!(mapValue.empty() && _ssExtra.empty()))
  680. {
  681. CDataStream ss(nType, nVersion);
  682. ss.insert(ss.begin(), '\0');
  683. ss << mapValue;
  684. ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
  685. strComment.append(ss.str());
  686. }
  687. }
  688. READWRITE(LIMITED_STRING(strComment, 65536));
  689. size_t nSepPos = strComment.find("\0", 0, 1);
  690. if (ser_action.ForRead())
  691. {
  692. mapValue.clear();
  693. if (std::string::npos != nSepPos)
  694. {
  695. CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
  696. ss >> mapValue;
  697. _ssExtra = std::vector<char>(ss.begin(), ss.end());
  698. }
  699. ReadOrderPos(nOrderPos, mapValue);
  700. }
  701. if (std::string::npos != nSepPos)
  702. strComment.erase(nSepPos);
  703. mapValue.erase("n");
  704. }
  705. private:
  706. std::vector<char> _ssExtra;
  707. };
  708. #endif // BITCOIN_WALLET_WALLET_H