Enable devirtualization opportunities by using the final specifier (C++11)
[bitcoinplatinum.git] / src / wallet / wallet.h
blob11ea89dc6ca56222011701790625dd2c6b9e04ac
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
9 #include "amount.h"
10 #include "policy/feerate.h"
11 #include "streams.h"
12 #include "tinyformat.h"
13 #include "ui_interface.h"
14 #include "utilstrencodings.h"
15 #include "validationinterface.h"
16 #include "script/ismine.h"
17 #include "script/sign.h"
18 #include "wallet/crypter.h"
19 #include "wallet/walletdb.h"
20 #include "wallet/rpcwallet.h"
22 #include <algorithm>
23 #include <atomic>
24 #include <map>
25 #include <set>
26 #include <stdexcept>
27 #include <stdint.h>
28 #include <string>
29 #include <utility>
30 #include <vector>
32 typedef CWallet* CWalletRef;
33 extern std::vector<CWalletRef> vpwallets;
35 /**
36 * Settings
38 extern CFeeRate payTxFee;
39 extern unsigned int nTxConfirmTarget;
40 extern bool bSpendZeroConfChange;
41 extern bool fWalletRbf;
43 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
44 //! -paytxfee default
45 static const CAmount DEFAULT_TRANSACTION_FEE = 0;
46 //! -fallbackfee default
47 static const CAmount DEFAULT_FALLBACK_FEE = 20000;
48 //! -mintxfee default
49 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
50 //! minimum recommended increment for BIP 125 replacement txs
51 static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
52 //! target minimum change amount
53 static const CAmount MIN_CHANGE = CENT;
54 //! final minimum change amount after paying for fees
55 static const CAmount MIN_FINAL_CHANGE = MIN_CHANGE/2;
56 //! Default for -spendzeroconfchange
57 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
58 //! Default for -walletrejectlongchains
59 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
60 //! -txconfirmtarget default
61 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
62 //! -walletrbf default
63 static const bool DEFAULT_WALLET_RBF = false;
64 static const bool DEFAULT_WALLETBROADCAST = true;
65 static const bool DEFAULT_DISABLE_WALLET = false;
66 //! if set, all keys will be derived by using BIP32
67 static const bool DEFAULT_USE_HD_WALLET = true;
69 extern const char * DEFAULT_WALLET_DAT;
71 static const int64_t TIMESTAMP_MIN = 0;
73 class CBlockIndex;
74 class CCoinControl;
75 class COutput;
76 class CReserveKey;
77 class CScript;
78 class CScheduler;
79 class CTxMemPool;
80 class CBlockPolicyEstimator;
81 class CWalletTx;
82 struct FeeCalculation;
83 enum class FeeEstimateMode;
85 /** (client) version numbers for particular wallet features */
86 enum WalletFeature
88 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
90 FEATURE_WALLETCRYPT = 40000, // wallet encryption
91 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
93 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
95 FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
97 FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
101 /** A key pool entry */
102 class CKeyPool
104 public:
105 int64_t nTime;
106 CPubKey vchPubKey;
107 bool fInternal; // for change outputs
109 CKeyPool();
110 CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
112 ADD_SERIALIZE_METHODS;
114 template <typename Stream, typename Operation>
115 inline void SerializationOp(Stream& s, Operation ser_action) {
116 int nVersion = s.GetVersion();
117 if (!(s.GetType() & SER_GETHASH))
118 READWRITE(nVersion);
119 READWRITE(nTime);
120 READWRITE(vchPubKey);
121 if (ser_action.ForRead()) {
122 try {
123 READWRITE(fInternal);
125 catch (std::ios_base::failure&) {
126 /* flag as external address if we can't read the internal boolean
127 (this will be the case for any wallet before the HD chain split version) */
128 fInternal = false;
131 else {
132 READWRITE(fInternal);
137 /** Address book data */
138 class CAddressBookData
140 public:
141 std::string name;
142 std::string purpose;
144 CAddressBookData() : purpose("unknown") {}
146 typedef std::map<std::string, std::string> StringMap;
147 StringMap destdata;
150 struct CRecipient
152 CScript scriptPubKey;
153 CAmount nAmount;
154 bool fSubtractFeeFromAmount;
157 typedef std::map<std::string, std::string> mapValue_t;
160 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
162 if (!mapValue.count("n"))
164 nOrderPos = -1; // TODO: calculate elsewhere
165 return;
167 nOrderPos = atoi64(mapValue["n"].c_str());
171 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
173 if (nOrderPos == -1)
174 return;
175 mapValue["n"] = i64tostr(nOrderPos);
178 struct COutputEntry
180 CTxDestination destination;
181 CAmount amount;
182 int vout;
185 /** A transaction with a merkle branch linking it to the block chain. */
186 class CMerkleTx
188 private:
189 /** Constant used in hashBlock to indicate tx has been abandoned */
190 static const uint256 ABANDON_HASH;
192 public:
193 CTransactionRef tx;
194 uint256 hashBlock;
196 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
197 * block in the chain we know this or any in-wallet dependency conflicts
198 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
199 * compatibility.
201 int nIndex;
203 CMerkleTx()
205 SetTx(MakeTransactionRef());
206 Init();
209 CMerkleTx(CTransactionRef arg)
211 SetTx(std::move(arg));
212 Init();
215 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
216 * TODO: adapt callers and remove this operator. */
217 operator const CTransaction&() const { return *tx; }
219 void Init()
221 hashBlock = uint256();
222 nIndex = -1;
225 void SetTx(CTransactionRef arg)
227 tx = std::move(arg);
230 ADD_SERIALIZE_METHODS;
232 template <typename Stream, typename Operation>
233 inline void SerializationOp(Stream& s, Operation ser_action) {
234 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
235 READWRITE(tx);
236 READWRITE(hashBlock);
237 READWRITE(vMerkleBranch);
238 READWRITE(nIndex);
241 void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
244 * Return depth of transaction in blockchain:
245 * <0 : conflicts with a transaction this deep in the blockchain
246 * 0 : in memory pool, waiting to be included in a block
247 * >=1 : this many blocks deep in the main chain
249 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
250 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
251 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
252 int GetBlocksToMaturity() const;
253 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
254 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
255 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
256 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
257 void setAbandoned() { hashBlock = ABANDON_HASH; }
259 const uint256& GetHash() const { return tx->GetHash(); }
260 bool IsCoinBase() const { return tx->IsCoinBase(); }
263 /**
264 * A transaction with a bunch of additional info that only the owner cares about.
265 * It includes any unrecorded transactions needed to link it back to the block chain.
267 class CWalletTx : public CMerkleTx
269 private:
270 const CWallet* pwallet;
272 public:
274 * Key/value map with information about the transaction.
276 * The following keys can be read and written through the map and are
277 * serialized in the wallet database:
279 * "comment", "to" - comment strings provided to sendtoaddress,
280 * sendfrom, sendmany wallet RPCs
281 * "replaces_txid" - txid (as HexStr) of transaction replaced by
282 * bumpfee on transaction created by bumpfee
283 * "replaced_by_txid" - txid (as HexStr) of transaction created by
284 * bumpfee on transaction replaced by bumpfee
285 * "from", "message" - obsolete fields that could be set in UI prior to
286 * 2011 (removed in commit 4d9b223)
288 * The following keys are serialized in the wallet database, but shouldn't
289 * be read or written through the map (they will be temporarily added and
290 * removed from the map during serialization):
292 * "fromaccount" - serialized strFromAccount value
293 * "n" - serialized nOrderPos value
294 * "timesmart" - serialized nTimeSmart value
295 * "spent" - serialized vfSpent value that existed prior to
296 * 2014 (removed in commit 93a18a3)
298 mapValue_t mapValue;
299 std::vector<std::pair<std::string, std::string> > vOrderForm;
300 unsigned int fTimeReceivedIsTxTime;
301 unsigned int nTimeReceived; //!< time received by this node
303 * Stable timestamp that never changes, and reflects the order a transaction
304 * was added to the wallet. Timestamp is based on the block time for a
305 * transaction added as part of a block, or else the time when the
306 * transaction was received if it wasn't part of a block, with the timestamp
307 * adjusted in both cases so timestamp order matches the order transactions
308 * were added to the wallet. More details can be found in
309 * CWallet::ComputeTimeSmart().
311 unsigned int nTimeSmart;
313 * From me flag is set to 1 for transactions that were created by the wallet
314 * on this bitcoin node, and set to 0 for transactions that were created
315 * externally and came in through the network or sendrawtransaction RPC.
317 char fFromMe;
318 std::string strFromAccount;
319 int64_t nOrderPos; //!< position in ordered transaction list
321 // memory only
322 mutable bool fDebitCached;
323 mutable bool fCreditCached;
324 mutable bool fImmatureCreditCached;
325 mutable bool fAvailableCreditCached;
326 mutable bool fWatchDebitCached;
327 mutable bool fWatchCreditCached;
328 mutable bool fImmatureWatchCreditCached;
329 mutable bool fAvailableWatchCreditCached;
330 mutable bool fChangeCached;
331 mutable CAmount nDebitCached;
332 mutable CAmount nCreditCached;
333 mutable CAmount nImmatureCreditCached;
334 mutable CAmount nAvailableCreditCached;
335 mutable CAmount nWatchDebitCached;
336 mutable CAmount nWatchCreditCached;
337 mutable CAmount nImmatureWatchCreditCached;
338 mutable CAmount nAvailableWatchCreditCached;
339 mutable CAmount nChangeCached;
341 CWalletTx()
343 Init(NULL);
346 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
348 Init(pwalletIn);
351 void Init(const CWallet* pwalletIn)
353 pwallet = pwalletIn;
354 mapValue.clear();
355 vOrderForm.clear();
356 fTimeReceivedIsTxTime = false;
357 nTimeReceived = 0;
358 nTimeSmart = 0;
359 fFromMe = false;
360 strFromAccount.clear();
361 fDebitCached = false;
362 fCreditCached = false;
363 fImmatureCreditCached = false;
364 fAvailableCreditCached = false;
365 fWatchDebitCached = false;
366 fWatchCreditCached = false;
367 fImmatureWatchCreditCached = false;
368 fAvailableWatchCreditCached = false;
369 fChangeCached = false;
370 nDebitCached = 0;
371 nCreditCached = 0;
372 nImmatureCreditCached = 0;
373 nAvailableCreditCached = 0;
374 nWatchDebitCached = 0;
375 nWatchCreditCached = 0;
376 nAvailableWatchCreditCached = 0;
377 nImmatureWatchCreditCached = 0;
378 nChangeCached = 0;
379 nOrderPos = -1;
382 ADD_SERIALIZE_METHODS;
384 template <typename Stream, typename Operation>
385 inline void SerializationOp(Stream& s, Operation ser_action) {
386 if (ser_action.ForRead())
387 Init(NULL);
388 char fSpent = false;
390 if (!ser_action.ForRead())
392 mapValue["fromaccount"] = strFromAccount;
394 WriteOrderPos(nOrderPos, mapValue);
396 if (nTimeSmart)
397 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
400 READWRITE(*(CMerkleTx*)this);
401 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
402 READWRITE(vUnused);
403 READWRITE(mapValue);
404 READWRITE(vOrderForm);
405 READWRITE(fTimeReceivedIsTxTime);
406 READWRITE(nTimeReceived);
407 READWRITE(fFromMe);
408 READWRITE(fSpent);
410 if (ser_action.ForRead())
412 strFromAccount = mapValue["fromaccount"];
414 ReadOrderPos(nOrderPos, mapValue);
416 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
419 mapValue.erase("fromaccount");
420 mapValue.erase("spent");
421 mapValue.erase("n");
422 mapValue.erase("timesmart");
425 //! make sure balances are recalculated
426 void MarkDirty()
428 fCreditCached = false;
429 fAvailableCreditCached = false;
430 fImmatureCreditCached = false;
431 fWatchDebitCached = false;
432 fWatchCreditCached = false;
433 fAvailableWatchCreditCached = false;
434 fImmatureWatchCreditCached = false;
435 fDebitCached = false;
436 fChangeCached = false;
439 void BindWallet(CWallet *pwalletIn)
441 pwallet = pwalletIn;
442 MarkDirty();
445 //! filter decides which addresses will count towards the debit
446 CAmount GetDebit(const isminefilter& filter) const;
447 CAmount GetCredit(const isminefilter& filter) const;
448 CAmount GetImmatureCredit(bool fUseCache=true) const;
449 CAmount GetAvailableCredit(bool fUseCache=true) const;
450 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
451 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
452 CAmount GetChange() const;
454 void GetAmounts(std::list<COutputEntry>& listReceived,
455 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
457 bool IsFromMe(const isminefilter& filter) const
459 return (GetDebit(filter) > 0);
462 // True if only scriptSigs are different
463 bool IsEquivalentTo(const CWalletTx& tx) const;
465 bool InMempool() const;
466 bool IsTrusted() const;
468 int64_t GetTxTime() const;
469 int GetRequestCount() const;
471 bool RelayWalletTransaction(CConnman* connman);
473 std::set<uint256> GetConflicts() const;
477 class CInputCoin {
478 public:
479 CInputCoin(const CWalletTx* walletTx, unsigned int i)
481 if (!walletTx)
482 throw std::invalid_argument("walletTx should not be null");
483 if (i >= walletTx->tx->vout.size())
484 throw std::out_of_range("The output index is out of range");
486 outpoint = COutPoint(walletTx->GetHash(), i);
487 txout = walletTx->tx->vout[i];
490 COutPoint outpoint;
491 CTxOut txout;
493 bool operator<(const CInputCoin& rhs) const {
494 return outpoint < rhs.outpoint;
497 bool operator!=(const CInputCoin& rhs) const {
498 return outpoint != rhs.outpoint;
501 bool operator==(const CInputCoin& rhs) const {
502 return outpoint == rhs.outpoint;
506 class COutput
508 public:
509 const CWalletTx *tx;
510 int i;
511 int nDepth;
513 /** Whether we have the private keys to spend this output */
514 bool fSpendable;
516 /** Whether we know how to spend this output, ignoring the lack of keys */
517 bool fSolvable;
520 * Whether this output is considered safe to spend. Unconfirmed transactions
521 * from outside keys and unconfirmed replacement transactions are considered
522 * unsafe and will not be used to fund new spending transactions.
524 bool fSafe;
526 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
528 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
531 std::string ToString() const;
537 /** Private key that includes an expiration date in case it never gets used. */
538 class CWalletKey
540 public:
541 CPrivKey vchPrivKey;
542 int64_t nTimeCreated;
543 int64_t nTimeExpires;
544 std::string strComment;
545 //! todo: add something to note what created it (user, getnewaddress, change)
546 //! maybe should have a map<string, string> property map
548 CWalletKey(int64_t nExpires=0);
550 ADD_SERIALIZE_METHODS;
552 template <typename Stream, typename Operation>
553 inline void SerializationOp(Stream& s, Operation ser_action) {
554 int nVersion = s.GetVersion();
555 if (!(s.GetType() & SER_GETHASH))
556 READWRITE(nVersion);
557 READWRITE(vchPrivKey);
558 READWRITE(nTimeCreated);
559 READWRITE(nTimeExpires);
560 READWRITE(LIMITED_STRING(strComment, 65536));
565 * Internal transfers.
566 * Database key is acentry<account><counter>.
568 class CAccountingEntry
570 public:
571 std::string strAccount;
572 CAmount nCreditDebit;
573 int64_t nTime;
574 std::string strOtherAccount;
575 std::string strComment;
576 mapValue_t mapValue;
577 int64_t nOrderPos; //!< position in ordered transaction list
578 uint64_t nEntryNo;
580 CAccountingEntry()
582 SetNull();
585 void SetNull()
587 nCreditDebit = 0;
588 nTime = 0;
589 strAccount.clear();
590 strOtherAccount.clear();
591 strComment.clear();
592 nOrderPos = -1;
593 nEntryNo = 0;
596 ADD_SERIALIZE_METHODS;
598 template <typename Stream, typename Operation>
599 inline void SerializationOp(Stream& s, Operation ser_action) {
600 int nVersion = s.GetVersion();
601 if (!(s.GetType() & SER_GETHASH))
602 READWRITE(nVersion);
603 //! Note: strAccount is serialized as part of the key, not here.
604 READWRITE(nCreditDebit);
605 READWRITE(nTime);
606 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
608 if (!ser_action.ForRead())
610 WriteOrderPos(nOrderPos, mapValue);
612 if (!(mapValue.empty() && _ssExtra.empty()))
614 CDataStream ss(s.GetType(), s.GetVersion());
615 ss.insert(ss.begin(), '\0');
616 ss << mapValue;
617 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
618 strComment.append(ss.str());
622 READWRITE(LIMITED_STRING(strComment, 65536));
624 size_t nSepPos = strComment.find("\0", 0, 1);
625 if (ser_action.ForRead())
627 mapValue.clear();
628 if (std::string::npos != nSepPos)
630 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
631 ss >> mapValue;
632 _ssExtra = std::vector<char>(ss.begin(), ss.end());
634 ReadOrderPos(nOrderPos, mapValue);
636 if (std::string::npos != nSepPos)
637 strComment.erase(nSepPos);
639 mapValue.erase("n");
642 private:
643 std::vector<char> _ssExtra;
647 /**
648 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
649 * and provides the ability to create new transactions.
651 class CWallet final : public CCryptoKeyStore, public CValidationInterface
653 private:
654 static std::atomic<bool> fFlushScheduled;
655 std::atomic<bool> fAbortRescan;
656 std::atomic<bool> fScanningWallet;
659 * Select a set of coins such that nValueRet >= nTargetValue and at least
660 * all coins from coinControl are selected; Never select unconfirmed coins
661 * if they are not ours
663 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
665 CWalletDB *pwalletdbEncryption;
667 //! the current wallet version: clients below this version are not able to load the wallet
668 int nWalletVersion;
670 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
671 int nWalletMaxVersion;
673 int64_t nNextResend;
674 int64_t nLastResend;
675 bool fBroadcastTransactions;
678 * Used to keep track of spent outpoints, and
679 * detect and report conflicts (double-spends or
680 * mutated transactions where the mutant gets mined).
682 typedef std::multimap<COutPoint, uint256> TxSpends;
683 TxSpends mapTxSpends;
684 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
685 void AddToSpends(const uint256& wtxid);
687 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
688 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
690 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
692 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
693 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
694 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = NULL, int posInBlock = 0);
696 /* the HD chain data model (external chain counters) */
697 CHDChain hdChain;
699 /* HD derive new child key (on internal or external chain) */
700 void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
702 std::set<int64_t> setInternalKeyPool;
703 std::set<int64_t> setExternalKeyPool;
705 int64_t nTimeFirstKey;
708 * Private version of AddWatchOnly method which does not accept a
709 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
710 * the watch key did not previously have a timestamp associated with it.
711 * Because this is an inherited virtual method, it is accessible despite
712 * being marked private, but it is marked private anyway to encourage use
713 * of the other AddWatchOnly which accepts a timestamp and sets
714 * nTimeFirstKey more intelligently for more efficient rescans.
716 bool AddWatchOnly(const CScript& dest) override;
718 std::unique_ptr<CWalletDBWrapper> dbw;
720 public:
722 * Main wallet lock.
723 * This lock protects all the fields added by CWallet.
725 mutable CCriticalSection cs_wallet;
727 /** Get database handle used by this wallet. Ideally this function would
728 * not be necessary.
730 CWalletDBWrapper& GetDBHandle()
732 return *dbw;
735 /** Get a name for this wallet for logging/debugging purposes.
737 std::string GetName() const
739 if (dbw) {
740 return dbw->GetName();
741 } else {
742 return "dummy";
746 void LoadKeyPool(int nIndex, const CKeyPool &keypool)
748 if (keypool.fInternal) {
749 setInternalKeyPool.insert(nIndex);
750 } else {
751 setExternalKeyPool.insert(nIndex);
754 // If no metadata exists yet, create a default with the pool key's
755 // creation time. Note that this may be overwritten by actually
756 // stored metadata for that key later, which is fine.
757 CKeyID keyid = keypool.vchPubKey.GetID();
758 if (mapKeyMetadata.count(keyid) == 0)
759 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
762 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
763 // key metadata.
764 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
766 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
767 MasterKeyMap mapMasterKeys;
768 unsigned int nMasterKeyMaxID;
770 // Create wallet with dummy database handle
771 CWallet(): dbw(new CWalletDBWrapper())
773 SetNull();
776 // Create wallet with passed-in database handle
777 CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
779 SetNull();
782 ~CWallet()
784 delete pwalletdbEncryption;
785 pwalletdbEncryption = NULL;
788 void SetNull()
790 nWalletVersion = FEATURE_BASE;
791 nWalletMaxVersion = FEATURE_BASE;
792 nMasterKeyMaxID = 0;
793 pwalletdbEncryption = NULL;
794 nOrderPosNext = 0;
795 nAccountingEntryNumber = 0;
796 nNextResend = 0;
797 nLastResend = 0;
798 nTimeFirstKey = 0;
799 fBroadcastTransactions = false;
800 nRelockTime = 0;
801 fAbortRescan = false;
802 fScanningWallet = false;
805 std::map<uint256, CWalletTx> mapWallet;
806 std::list<CAccountingEntry> laccentries;
808 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
809 typedef std::multimap<int64_t, TxPair > TxItems;
810 TxItems wtxOrdered;
812 int64_t nOrderPosNext;
813 uint64_t nAccountingEntryNumber;
814 std::map<uint256, int> mapRequestCount;
816 std::map<CTxDestination, CAddressBookData> mapAddressBook;
818 CPubKey vchDefaultKey;
820 std::set<COutPoint> setLockedCoins;
822 const CWalletTx* GetWalletTx(const uint256& hash) const;
824 //! check whether we are allowed to upgrade (or already support) to the named feature
825 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
828 * populate vCoins with vector of available COutputs.
830 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe=true, const CCoinControl *coinControl = NULL, const CAmount& nMinimumAmount = 1, const CAmount& nMaximumAmount = MAX_MONEY, const CAmount& nMinimumSumAmount = MAX_MONEY, const uint64_t& nMaximumCount = 0, const int& nMinDepth = 0, const int& nMaxDepth = 9999999) const;
833 * Return list of available coins and locked coins grouped by non-change output address.
835 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
838 * Find non-change parent output.
840 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
843 * Shuffle and select coins until nTargetValue is reached while avoiding
844 * small change; This method is stochastic for some inputs and upon
845 * completion the coin set and corresponding actual target value is
846 * assembled
848 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
850 bool IsSpent(const uint256& hash, unsigned int n) const;
852 bool IsLockedCoin(uint256 hash, unsigned int n) const;
853 void LockCoin(const COutPoint& output);
854 void UnlockCoin(const COutPoint& output);
855 void UnlockAllCoins();
856 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
859 * Rescan abort properties
861 void AbortRescan() { fAbortRescan = true; }
862 bool IsAbortingRescan() { return fAbortRescan; }
863 bool IsScanning() { return fScanningWallet; }
866 * keystore implementation
867 * Generate a new key
869 CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
870 //! Adds a key to the store, and saves it to disk.
871 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
872 bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
873 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
874 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
875 //! Load metadata (used by LoadWallet)
876 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
878 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
879 void UpdateTimeFirstKey(int64_t nCreateTime);
881 //! Adds an encrypted key to the store, and saves it to disk.
882 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
883 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
884 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
885 bool AddCScript(const CScript& redeemScript) override;
886 bool LoadCScript(const CScript& redeemScript);
888 //! Adds a destination data tuple to the store, and saves it to disk
889 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
890 //! Erases a destination data tuple in the store and on disk
891 bool EraseDestData(const CTxDestination &dest, const std::string &key);
892 //! Adds a destination data tuple to the store, without saving it to disk
893 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
894 //! Look up a destination data tuple in the store, return true if found false otherwise
895 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
896 //! Get all destination values matching a prefix.
897 std::vector<std::string> GetDestValues(const std::string& prefix) const;
899 //! Adds a watch-only address to the store, and saves it to disk.
900 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
901 bool RemoveWatchOnly(const CScript &dest) override;
902 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
903 bool LoadWatchOnly(const CScript &dest);
905 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
906 int64_t nRelockTime;
908 bool Unlock(const SecureString& strWalletPassphrase);
909 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
910 bool EncryptWallet(const SecureString& strWalletPassphrase);
912 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
913 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
915 /**
916 * Increment the next transaction order id
917 * @return next transaction order id
919 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
920 DBErrors ReorderTransactions();
921 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
922 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
924 void MarkDirty();
925 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
926 bool LoadToWallet(const CWalletTx& wtxIn);
927 void TransactionAddedToMempool(const CTransactionRef& tx) override;
928 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
929 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
930 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
931 int64_t RescanFromTime(int64_t startTime, bool update);
932 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
933 void ReacceptWalletTransactions();
934 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
935 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
936 CAmount GetBalance() const;
937 CAmount GetUnconfirmedBalance() const;
938 CAmount GetImmatureBalance() const;
939 CAmount GetWatchOnlyBalance() const;
940 CAmount GetUnconfirmedWatchOnlyBalance() const;
941 CAmount GetImmatureWatchOnlyBalance() const;
942 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
943 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
946 * Insert additional inputs into the transaction by
947 * calling CreateTransaction();
949 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl, bool keepReserveKey = true);
950 bool SignTransaction(CMutableTransaction& tx);
953 * Create a new transaction paying the recipients with a set of coins
954 * selected by SelectCoins(); Also create the change output, when needed
955 * @note passing nChangePosInOut as -1 will result in setting a random position
957 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
958 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
959 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
961 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
962 bool AddAccountingEntry(const CAccountingEntry&);
963 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
964 template <typename ContainerType>
965 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
967 static CFeeRate minTxFee;
968 static CFeeRate fallbackFee;
970 * Estimate the minimum fee considering user set parameters
971 * and the required fee
973 static CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
975 * Return the minimum required fee taking into account the
976 * floating relay fee and user set minimum transaction fee
978 static CAmount GetRequiredFee(unsigned int nTxBytes);
980 bool NewKeyPool();
981 size_t KeypoolCountExternalKeys();
982 bool TopUpKeyPool(unsigned int kpSize = 0);
983 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
984 void KeepKey(int64_t nIndex);
985 void ReturnKey(int64_t nIndex, bool fInternal);
986 bool GetKeyFromPool(CPubKey &key, bool internal = false);
987 int64_t GetOldestKeyPoolTime();
988 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
990 std::set< std::set<CTxDestination> > GetAddressGroupings();
991 std::map<CTxDestination, CAmount> GetAddressBalances();
993 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
995 isminetype IsMine(const CTxIn& txin) const;
997 * Returns amount of debit if the input matches the
998 * filter, otherwise returns 0
1000 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1001 isminetype IsMine(const CTxOut& txout) const;
1002 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1003 bool IsChange(const CTxOut& txout) const;
1004 CAmount GetChange(const CTxOut& txout) const;
1005 bool IsMine(const CTransaction& tx) const;
1006 /** should probably be renamed to IsRelevantToMe */
1007 bool IsFromMe(const CTransaction& tx) const;
1008 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1009 /** Returns whether all of the inputs match the filter */
1010 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1011 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1012 CAmount GetChange(const CTransaction& tx) const;
1013 void SetBestChain(const CBlockLocator& loc) override;
1015 DBErrors LoadWallet(bool& fFirstRunRet);
1016 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1017 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1019 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1021 bool DelAddressBook(const CTxDestination& address);
1023 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1025 void Inventory(const uint256 &hash) override
1028 LOCK(cs_wallet);
1029 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1030 if (mi != mapRequestCount.end())
1031 (*mi).second++;
1035 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1037 unsigned int GetKeyPoolSize()
1039 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1040 return setInternalKeyPool.size() + setExternalKeyPool.size();
1043 bool SetDefaultKey(const CPubKey &vchPubKey);
1045 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1046 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
1048 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1049 bool SetMaxVersion(int nVersion);
1051 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1052 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1054 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1055 std::set<uint256> GetConflicts(const uint256& txid) const;
1057 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1058 bool HasWalletSpend(const uint256& txid) const;
1060 //! Flush wallet (bitdb flush)
1061 void Flush(bool shutdown=false);
1063 //! Verify the wallet database and perform salvage if required
1064 static bool Verify();
1066 /**
1067 * Address book entry changed.
1068 * @note called with lock cs_wallet held.
1070 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1071 &address, const std::string &label, bool isMine,
1072 const std::string &purpose,
1073 ChangeType status)> NotifyAddressBookChanged;
1075 /**
1076 * Wallet transaction added, removed or updated.
1077 * @note called with lock cs_wallet held.
1079 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1080 ChangeType status)> NotifyTransactionChanged;
1082 /** Show progress e.g. for rescan */
1083 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1085 /** Watch-only address added */
1086 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1088 /** Inquire whether this wallet broadcasts transactions. */
1089 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1090 /** Set whether this wallet broadcasts transactions. */
1091 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1093 /** Return whether transaction can be abandoned */
1094 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1096 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1097 bool AbandonTransaction(const uint256& hashTx);
1099 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1100 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1102 /* Returns the wallets help message */
1103 static std::string GetWalletHelpString(bool showDebug);
1105 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1106 static CWallet* CreateWalletFromFile(const std::string walletFile);
1107 static bool InitLoadWallet();
1110 * Wallet post-init setup
1111 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1113 void postInitProcess(CScheduler& scheduler);
1115 /* Wallets parameter interaction */
1116 static bool ParameterInteraction();
1118 bool BackupWallet(const std::string& strDest);
1120 /* Set the HD chain model (chain child index counters) */
1121 bool SetHDChain(const CHDChain& chain, bool memonly);
1122 const CHDChain& GetHDChain() const { return hdChain; }
1124 /* Returns true if HD is enabled */
1125 bool IsHDEnabled() const;
1127 /* Generates a new HD master key (will not be activated) */
1128 CPubKey GenerateNewHDMasterKey();
1130 /* Set the current HD master key (will reset the chain child index counters)
1131 Sets the master key's version based on the current wallet version (so the
1132 caller must ensure the current wallet version is correct before calling
1133 this function). */
1134 bool SetHDMasterKey(const CPubKey& key);
1137 /** A key allocated from the key pool. */
1138 class CReserveKey final : public CReserveScript
1140 protected:
1141 CWallet* pwallet;
1142 int64_t nIndex;
1143 CPubKey vchPubKey;
1144 bool fInternal;
1145 public:
1146 CReserveKey(CWallet* pwalletIn)
1148 nIndex = -1;
1149 pwallet = pwalletIn;
1150 fInternal = false;
1153 CReserveKey() = default;
1154 CReserveKey(const CReserveKey&) = delete;
1155 CReserveKey& operator=(const CReserveKey&) = delete;
1157 ~CReserveKey()
1159 ReturnKey();
1162 void ReturnKey();
1163 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1164 void KeepKey();
1165 void KeepScript() override { KeepKey(); }
1169 /**
1170 * Account information.
1171 * Stored in wallet with key "acc"+string account name.
1173 class CAccount
1175 public:
1176 CPubKey vchPubKey;
1178 CAccount()
1180 SetNull();
1183 void SetNull()
1185 vchPubKey = CPubKey();
1188 ADD_SERIALIZE_METHODS;
1190 template <typename Stream, typename Operation>
1191 inline void SerializationOp(Stream& s, Operation ser_action) {
1192 int nVersion = s.GetVersion();
1193 if (!(s.GetType() & SER_GETHASH))
1194 READWRITE(nVersion);
1195 READWRITE(vchPubKey);
1199 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1200 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1201 // so that each entry corresponds to each vIn, in order.
1202 template <typename ContainerType>
1203 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1205 // Fill in dummy signatures for fee calculation.
1206 int nIn = 0;
1207 for (const auto& coin : coins)
1209 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1210 SignatureData sigdata;
1212 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1214 return false;
1215 } else {
1216 UpdateTransaction(txNew, nIn, sigdata);
1219 nIn++;
1221 return true;
1224 #endif // BITCOIN_WALLET_WALLET_H