Merge #8694: Basic multiwallet support
[bitcoinplatinum.git] / src / wallet / wallet.h
blob6c6eb69180ae630857d2a610742f35496f9d500d
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 = 100;
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 class CBlockIndex;
72 class CCoinControl;
73 class COutput;
74 class CReserveKey;
75 class CScript;
76 class CScheduler;
77 class CTxMemPool;
78 class CBlockPolicyEstimator;
79 class CWalletTx;
81 /** (client) version numbers for particular wallet features */
82 enum WalletFeature
84 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
86 FEATURE_WALLETCRYPT = 40000, // wallet encryption
87 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
89 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
91 FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
93 FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
97 /** A key pool entry */
98 class CKeyPool
100 public:
101 int64_t nTime;
102 CPubKey vchPubKey;
103 bool fInternal; // for change outputs
105 CKeyPool();
106 CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
108 ADD_SERIALIZE_METHODS;
110 template <typename Stream, typename Operation>
111 inline void SerializationOp(Stream& s, Operation ser_action) {
112 int nVersion = s.GetVersion();
113 if (!(s.GetType() & SER_GETHASH))
114 READWRITE(nVersion);
115 READWRITE(nTime);
116 READWRITE(vchPubKey);
117 if (ser_action.ForRead()) {
118 try {
119 READWRITE(fInternal);
121 catch (std::ios_base::failure&) {
122 /* flag as external address if we can't read the internal boolean
123 (this will be the case for any wallet before the HD chain split version) */
124 fInternal = false;
127 else {
128 READWRITE(fInternal);
133 /** Address book data */
134 class CAddressBookData
136 public:
137 std::string name;
138 std::string purpose;
140 CAddressBookData() : purpose("unknown") {}
142 typedef std::map<std::string, std::string> StringMap;
143 StringMap destdata;
146 struct CRecipient
148 CScript scriptPubKey;
149 CAmount nAmount;
150 bool fSubtractFeeFromAmount;
153 typedef std::map<std::string, std::string> mapValue_t;
156 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
158 if (!mapValue.count("n"))
160 nOrderPos = -1; // TODO: calculate elsewhere
161 return;
163 nOrderPos = atoi64(mapValue["n"].c_str());
167 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
169 if (nOrderPos == -1)
170 return;
171 mapValue["n"] = i64tostr(nOrderPos);
174 struct COutputEntry
176 CTxDestination destination;
177 CAmount amount;
178 int vout;
181 /** A transaction with a merkle branch linking it to the block chain. */
182 class CMerkleTx
184 private:
185 /** Constant used in hashBlock to indicate tx has been abandoned */
186 static const uint256 ABANDON_HASH;
188 public:
189 CTransactionRef tx;
190 uint256 hashBlock;
192 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
193 * block in the chain we know this or any in-wallet dependency conflicts
194 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
195 * compatibility.
197 int nIndex;
199 CMerkleTx()
201 SetTx(MakeTransactionRef());
202 Init();
205 CMerkleTx(CTransactionRef arg)
207 SetTx(std::move(arg));
208 Init();
211 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
212 * TODO: adapt callers and remove this operator. */
213 operator const CTransaction&() const { return *tx; }
215 void Init()
217 hashBlock = uint256();
218 nIndex = -1;
221 void SetTx(CTransactionRef arg)
223 tx = std::move(arg);
226 ADD_SERIALIZE_METHODS;
228 template <typename Stream, typename Operation>
229 inline void SerializationOp(Stream& s, Operation ser_action) {
230 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
231 READWRITE(tx);
232 READWRITE(hashBlock);
233 READWRITE(vMerkleBranch);
234 READWRITE(nIndex);
237 void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
240 * Return depth of transaction in blockchain:
241 * <0 : conflicts with a transaction this deep in the blockchain
242 * 0 : in memory pool, waiting to be included in a block
243 * >=1 : this many blocks deep in the main chain
245 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
246 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
247 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
248 int GetBlocksToMaturity() const;
249 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
250 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
251 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
252 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
253 void setAbandoned() { hashBlock = ABANDON_HASH; }
255 const uint256& GetHash() const { return tx->GetHash(); }
256 bool IsCoinBase() const { return tx->IsCoinBase(); }
259 /**
260 * A transaction with a bunch of additional info that only the owner cares about.
261 * It includes any unrecorded transactions needed to link it back to the block chain.
263 class CWalletTx : public CMerkleTx
265 private:
266 const CWallet* pwallet;
268 public:
270 * Key/value map with information about the transaction.
272 * The following keys can be read and written through the map and are
273 * serialized in the wallet database:
275 * "comment", "to" - comment strings provided to sendtoaddress,
276 * sendfrom, sendmany wallet RPCs
277 * "replaces_txid" - txid (as HexStr) of transaction replaced by
278 * bumpfee on transaction created by bumpfee
279 * "replaced_by_txid" - txid (as HexStr) of transaction created by
280 * bumpfee on transaction replaced by bumpfee
281 * "from", "message" - obsolete fields that could be set in UI prior to
282 * 2011 (removed in commit 4d9b223)
284 * The following keys are serialized in the wallet database, but shouldn't
285 * be read or written through the map (they will be temporarily added and
286 * removed from the map during serialization):
288 * "fromaccount" - serialized strFromAccount value
289 * "n" - serialized nOrderPos value
290 * "timesmart" - serialized nTimeSmart value
291 * "spent" - serialized vfSpent value that existed prior to
292 * 2014 (removed in commit 93a18a3)
294 mapValue_t mapValue;
295 std::vector<std::pair<std::string, std::string> > vOrderForm;
296 unsigned int fTimeReceivedIsTxTime;
297 unsigned int nTimeReceived; //!< time received by this node
299 * Stable timestamp that never changes, and reflects the order a transaction
300 * was added to the wallet. Timestamp is based on the block time for a
301 * transaction added as part of a block, or else the time when the
302 * transaction was received if it wasn't part of a block, with the timestamp
303 * adjusted in both cases so timestamp order matches the order transactions
304 * were added to the wallet. More details can be found in
305 * CWallet::ComputeTimeSmart().
307 unsigned int nTimeSmart;
309 * From me flag is set to 1 for transactions that were created by the wallet
310 * on this bitcoin node, and set to 0 for transactions that were created
311 * externally and came in through the network or sendrawtransaction RPC.
313 char fFromMe;
314 std::string strFromAccount;
315 int64_t nOrderPos; //!< position in ordered transaction list
317 // memory only
318 mutable bool fDebitCached;
319 mutable bool fCreditCached;
320 mutable bool fImmatureCreditCached;
321 mutable bool fAvailableCreditCached;
322 mutable bool fWatchDebitCached;
323 mutable bool fWatchCreditCached;
324 mutable bool fImmatureWatchCreditCached;
325 mutable bool fAvailableWatchCreditCached;
326 mutable bool fChangeCached;
327 mutable CAmount nDebitCached;
328 mutable CAmount nCreditCached;
329 mutable CAmount nImmatureCreditCached;
330 mutable CAmount nAvailableCreditCached;
331 mutable CAmount nWatchDebitCached;
332 mutable CAmount nWatchCreditCached;
333 mutable CAmount nImmatureWatchCreditCached;
334 mutable CAmount nAvailableWatchCreditCached;
335 mutable CAmount nChangeCached;
337 CWalletTx()
339 Init(NULL);
342 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
344 Init(pwalletIn);
347 void Init(const CWallet* pwalletIn)
349 pwallet = pwalletIn;
350 mapValue.clear();
351 vOrderForm.clear();
352 fTimeReceivedIsTxTime = false;
353 nTimeReceived = 0;
354 nTimeSmart = 0;
355 fFromMe = false;
356 strFromAccount.clear();
357 fDebitCached = false;
358 fCreditCached = false;
359 fImmatureCreditCached = false;
360 fAvailableCreditCached = false;
361 fWatchDebitCached = false;
362 fWatchCreditCached = false;
363 fImmatureWatchCreditCached = false;
364 fAvailableWatchCreditCached = false;
365 fChangeCached = false;
366 nDebitCached = 0;
367 nCreditCached = 0;
368 nImmatureCreditCached = 0;
369 nAvailableCreditCached = 0;
370 nWatchDebitCached = 0;
371 nWatchCreditCached = 0;
372 nAvailableWatchCreditCached = 0;
373 nImmatureWatchCreditCached = 0;
374 nChangeCached = 0;
375 nOrderPos = -1;
378 ADD_SERIALIZE_METHODS;
380 template <typename Stream, typename Operation>
381 inline void SerializationOp(Stream& s, Operation ser_action) {
382 if (ser_action.ForRead())
383 Init(NULL);
384 char fSpent = false;
386 if (!ser_action.ForRead())
388 mapValue["fromaccount"] = strFromAccount;
390 WriteOrderPos(nOrderPos, mapValue);
392 if (nTimeSmart)
393 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
396 READWRITE(*(CMerkleTx*)this);
397 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
398 READWRITE(vUnused);
399 READWRITE(mapValue);
400 READWRITE(vOrderForm);
401 READWRITE(fTimeReceivedIsTxTime);
402 READWRITE(nTimeReceived);
403 READWRITE(fFromMe);
404 READWRITE(fSpent);
406 if (ser_action.ForRead())
408 strFromAccount = mapValue["fromaccount"];
410 ReadOrderPos(nOrderPos, mapValue);
412 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
415 mapValue.erase("fromaccount");
416 mapValue.erase("spent");
417 mapValue.erase("n");
418 mapValue.erase("timesmart");
421 //! make sure balances are recalculated
422 void MarkDirty()
424 fCreditCached = false;
425 fAvailableCreditCached = false;
426 fImmatureCreditCached = false;
427 fWatchDebitCached = false;
428 fWatchCreditCached = false;
429 fAvailableWatchCreditCached = false;
430 fImmatureWatchCreditCached = false;
431 fDebitCached = false;
432 fChangeCached = false;
435 void BindWallet(CWallet *pwalletIn)
437 pwallet = pwalletIn;
438 MarkDirty();
441 //! filter decides which addresses will count towards the debit
442 CAmount GetDebit(const isminefilter& filter) const;
443 CAmount GetCredit(const isminefilter& filter) const;
444 CAmount GetImmatureCredit(bool fUseCache=true) const;
445 CAmount GetAvailableCredit(bool fUseCache=true) const;
446 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
447 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
448 CAmount GetChange() const;
450 void GetAmounts(std::list<COutputEntry>& listReceived,
451 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
453 bool IsFromMe(const isminefilter& filter) const
455 return (GetDebit(filter) > 0);
458 // True if only scriptSigs are different
459 bool IsEquivalentTo(const CWalletTx& tx) const;
461 bool InMempool() const;
462 bool IsTrusted() const;
464 int64_t GetTxTime() const;
465 int GetRequestCount() const;
467 bool RelayWalletTransaction(CConnman* connman);
469 std::set<uint256> GetConflicts() const;
473 class CInputCoin {
474 public:
475 CInputCoin(const CWalletTx* walletTx, unsigned int i)
477 if (!walletTx)
478 throw std::invalid_argument("walletTx should not be null");
479 if (i >= walletTx->tx->vout.size())
480 throw std::out_of_range("The output index is out of range");
482 outpoint = COutPoint(walletTx->GetHash(), i);
483 txout = walletTx->tx->vout[i];
486 COutPoint outpoint;
487 CTxOut txout;
489 bool operator<(const CInputCoin& rhs) const {
490 return outpoint < rhs.outpoint;
493 bool operator!=(const CInputCoin& rhs) const {
494 return outpoint != rhs.outpoint;
497 bool operator==(const CInputCoin& rhs) const {
498 return outpoint == rhs.outpoint;
502 class COutput
504 public:
505 const CWalletTx *tx;
506 int i;
507 int nDepth;
509 /** Whether we have the private keys to spend this output */
510 bool fSpendable;
512 /** Whether we know how to spend this output, ignoring the lack of keys */
513 bool fSolvable;
516 * Whether this output is considered safe to spend. Unconfirmed transactions
517 * from outside keys and unconfirmed replacement transactions are considered
518 * unsafe and will not be used to fund new spending transactions.
520 bool fSafe;
522 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
524 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
527 std::string ToString() const;
533 /** Private key that includes an expiration date in case it never gets used. */
534 class CWalletKey
536 public:
537 CPrivKey vchPrivKey;
538 int64_t nTimeCreated;
539 int64_t nTimeExpires;
540 std::string strComment;
541 //! todo: add something to note what created it (user, getnewaddress, change)
542 //! maybe should have a map<string, string> property map
544 CWalletKey(int64_t nExpires=0);
546 ADD_SERIALIZE_METHODS;
548 template <typename Stream, typename Operation>
549 inline void SerializationOp(Stream& s, Operation ser_action) {
550 int nVersion = s.GetVersion();
551 if (!(s.GetType() & SER_GETHASH))
552 READWRITE(nVersion);
553 READWRITE(vchPrivKey);
554 READWRITE(nTimeCreated);
555 READWRITE(nTimeExpires);
556 READWRITE(LIMITED_STRING(strComment, 65536));
561 * Internal transfers.
562 * Database key is acentry<account><counter>.
564 class CAccountingEntry
566 public:
567 std::string strAccount;
568 CAmount nCreditDebit;
569 int64_t nTime;
570 std::string strOtherAccount;
571 std::string strComment;
572 mapValue_t mapValue;
573 int64_t nOrderPos; //!< position in ordered transaction list
574 uint64_t nEntryNo;
576 CAccountingEntry()
578 SetNull();
581 void SetNull()
583 nCreditDebit = 0;
584 nTime = 0;
585 strAccount.clear();
586 strOtherAccount.clear();
587 strComment.clear();
588 nOrderPos = -1;
589 nEntryNo = 0;
592 ADD_SERIALIZE_METHODS;
594 template <typename Stream, typename Operation>
595 inline void SerializationOp(Stream& s, Operation ser_action) {
596 int nVersion = s.GetVersion();
597 if (!(s.GetType() & SER_GETHASH))
598 READWRITE(nVersion);
599 //! Note: strAccount is serialized as part of the key, not here.
600 READWRITE(nCreditDebit);
601 READWRITE(nTime);
602 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
604 if (!ser_action.ForRead())
606 WriteOrderPos(nOrderPos, mapValue);
608 if (!(mapValue.empty() && _ssExtra.empty()))
610 CDataStream ss(s.GetType(), s.GetVersion());
611 ss.insert(ss.begin(), '\0');
612 ss << mapValue;
613 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
614 strComment.append(ss.str());
618 READWRITE(LIMITED_STRING(strComment, 65536));
620 size_t nSepPos = strComment.find("\0", 0, 1);
621 if (ser_action.ForRead())
623 mapValue.clear();
624 if (std::string::npos != nSepPos)
626 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
627 ss >> mapValue;
628 _ssExtra = std::vector<char>(ss.begin(), ss.end());
630 ReadOrderPos(nOrderPos, mapValue);
632 if (std::string::npos != nSepPos)
633 strComment.erase(nSepPos);
635 mapValue.erase("n");
638 private:
639 std::vector<char> _ssExtra;
643 /**
644 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
645 * and provides the ability to create new transactions.
647 class CWallet : public CCryptoKeyStore, public CValidationInterface
649 private:
650 static std::atomic<bool> fFlushScheduled;
651 std::atomic<bool> fAbortRescan;
652 std::atomic<bool> fScanningWallet;
655 * Select a set of coins such that nValueRet >= nTargetValue and at least
656 * all coins from coinControl are selected; Never select unconfirmed coins
657 * if they are not ours
659 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
661 CWalletDB *pwalletdbEncryption;
663 //! the current wallet version: clients below this version are not able to load the wallet
664 int nWalletVersion;
666 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
667 int nWalletMaxVersion;
669 int64_t nNextResend;
670 int64_t nLastResend;
671 bool fBroadcastTransactions;
674 * Used to keep track of spent outpoints, and
675 * detect and report conflicts (double-spends or
676 * mutated transactions where the mutant gets mined).
678 typedef std::multimap<COutPoint, uint256> TxSpends;
679 TxSpends mapTxSpends;
680 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
681 void AddToSpends(const uint256& wtxid);
683 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
684 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
686 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
688 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
689 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
690 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = NULL, int posInBlock = 0);
692 /* the HD chain data model (external chain counters) */
693 CHDChain hdChain;
695 /* HD derive new child key (on internal or external chain) */
696 void DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret, bool internal = false);
698 std::set<int64_t> setKeyPool;
700 int64_t nTimeFirstKey;
703 * Private version of AddWatchOnly method which does not accept a
704 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
705 * the watch key did not previously have a timestamp associated with it.
706 * Because this is an inherited virtual method, it is accessible despite
707 * being marked private, but it is marked private anyway to encourage use
708 * of the other AddWatchOnly which accepts a timestamp and sets
709 * nTimeFirstKey more intelligently for more efficient rescans.
711 bool AddWatchOnly(const CScript& dest) override;
713 std::unique_ptr<CWalletDBWrapper> dbw;
715 public:
717 * Main wallet lock.
718 * This lock protects all the fields added by CWallet.
720 mutable CCriticalSection cs_wallet;
722 /** Get database handle used by this wallet. Ideally this function would
723 * not be necessary.
725 CWalletDBWrapper& GetDBHandle()
727 return *dbw;
730 /** Get a name for this wallet for logging/debugging purposes.
732 std::string GetName() const
734 if (dbw) {
735 return dbw->GetName();
736 } else {
737 return "dummy";
741 void LoadKeyPool(int nIndex, const CKeyPool &keypool)
743 setKeyPool.insert(nIndex);
745 // If no metadata exists yet, create a default with the pool key's
746 // creation time. Note that this may be overwritten by actually
747 // stored metadata for that key later, which is fine.
748 CKeyID keyid = keypool.vchPubKey.GetID();
749 if (mapKeyMetadata.count(keyid) == 0)
750 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
753 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
754 // key metadata.
755 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
757 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
758 MasterKeyMap mapMasterKeys;
759 unsigned int nMasterKeyMaxID;
761 // Create wallet with dummy database handle
762 CWallet(): dbw(new CWalletDBWrapper())
764 SetNull();
767 // Create wallet with passed-in database handle
768 CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
770 SetNull();
773 ~CWallet()
775 delete pwalletdbEncryption;
776 pwalletdbEncryption = NULL;
779 void SetNull()
781 nWalletVersion = FEATURE_BASE;
782 nWalletMaxVersion = FEATURE_BASE;
783 nMasterKeyMaxID = 0;
784 pwalletdbEncryption = NULL;
785 nOrderPosNext = 0;
786 nAccountingEntryNumber = 0;
787 nNextResend = 0;
788 nLastResend = 0;
789 nTimeFirstKey = 0;
790 fBroadcastTransactions = false;
791 nRelockTime = 0;
792 fAbortRescan = false;
793 fScanningWallet = false;
796 std::map<uint256, CWalletTx> mapWallet;
797 std::list<CAccountingEntry> laccentries;
799 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
800 typedef std::multimap<int64_t, TxPair > TxItems;
801 TxItems wtxOrdered;
803 int64_t nOrderPosNext;
804 uint64_t nAccountingEntryNumber;
805 std::map<uint256, int> mapRequestCount;
807 std::map<CTxDestination, CAddressBookData> mapAddressBook;
809 CPubKey vchDefaultKey;
811 std::set<COutPoint> setLockedCoins;
813 const CWalletTx* GetWalletTx(const uint256& hash) const;
815 //! check whether we are allowed to upgrade (or already support) to the named feature
816 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
819 * populate vCoins with vector of available COutputs.
821 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;
824 * Return list of available coins and locked coins grouped by non-change output address.
826 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
829 * Find non-change parent output.
831 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
834 * Shuffle and select coins until nTargetValue is reached while avoiding
835 * small change; This method is stochastic for some inputs and upon
836 * completion the coin set and corresponding actual target value is
837 * assembled
839 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
841 bool IsSpent(const uint256& hash, unsigned int n) const;
843 bool IsLockedCoin(uint256 hash, unsigned int n) const;
844 void LockCoin(const COutPoint& output);
845 void UnlockCoin(const COutPoint& output);
846 void UnlockAllCoins();
847 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
850 * Rescan abort properties
852 void AbortRescan() { fAbortRescan = true; }
853 bool IsAbortingRescan() { return fAbortRescan; }
854 bool IsScanning() { return fScanningWallet; }
857 * keystore implementation
858 * Generate a new key
860 CPubKey GenerateNewKey(bool internal = false);
861 //! Adds a key to the store, and saves it to disk.
862 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
863 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
864 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
865 //! Load metadata (used by LoadWallet)
866 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
868 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
869 void UpdateTimeFirstKey(int64_t nCreateTime);
871 //! Adds an encrypted key to the store, and saves it to disk.
872 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
873 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
874 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
875 bool AddCScript(const CScript& redeemScript) override;
876 bool LoadCScript(const CScript& redeemScript);
878 //! Adds a destination data tuple to the store, and saves it to disk
879 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
880 //! Erases a destination data tuple in the store and on disk
881 bool EraseDestData(const CTxDestination &dest, const std::string &key);
882 //! Adds a destination data tuple to the store, without saving it to disk
883 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
884 //! Look up a destination data tuple in the store, return true if found false otherwise
885 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
886 //! Get all destination values matching a prefix.
887 std::vector<std::string> GetDestValues(const std::string& prefix) const;
889 //! Adds a watch-only address to the store, and saves it to disk.
890 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
891 bool RemoveWatchOnly(const CScript &dest) override;
892 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
893 bool LoadWatchOnly(const CScript &dest);
895 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
896 int64_t nRelockTime;
898 bool Unlock(const SecureString& strWalletPassphrase);
899 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
900 bool EncryptWallet(const SecureString& strWalletPassphrase);
902 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
903 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
905 /**
906 * Increment the next transaction order id
907 * @return next transaction order id
909 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
910 DBErrors ReorderTransactions();
911 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
912 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
914 void MarkDirty();
915 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
916 bool LoadToWallet(const CWalletTx& wtxIn);
917 void TransactionAddedToMempool(const CTransactionRef& tx) override;
918 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
919 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
920 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
921 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
922 void ReacceptWalletTransactions();
923 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
924 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
925 CAmount GetBalance() const;
926 CAmount GetUnconfirmedBalance() const;
927 CAmount GetImmatureBalance() const;
928 CAmount GetWatchOnlyBalance() const;
929 CAmount GetUnconfirmedWatchOnlyBalance() const;
930 CAmount GetImmatureWatchOnlyBalance() const;
931 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
932 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
935 * Insert additional inputs into the transaction by
936 * calling CreateTransaction();
938 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl, bool keepReserveKey = true);
939 bool SignTransaction(CMutableTransaction& tx);
942 * Create a new transaction paying the recipients with a set of coins
943 * selected by SelectCoins(); Also create the change output, when needed
944 * @note passing nChangePosInOut as -1 will result in setting a random position
946 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
947 std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true);
948 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
950 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
951 bool AddAccountingEntry(const CAccountingEntry&);
952 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
953 template <typename ContainerType>
954 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
956 static CFeeRate minTxFee;
957 static CFeeRate fallbackFee;
959 * Estimate the minimum fee considering user set parameters
960 * and the required fee
962 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee = false);
964 * Return the minimum required fee taking into account the
965 * floating relay fee and user set minimum transaction fee
967 static CAmount GetRequiredFee(unsigned int nTxBytes);
969 bool NewKeyPool();
970 size_t KeypoolCountExternalKeys();
971 bool TopUpKeyPool(unsigned int kpSize = 0);
972 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal);
973 void KeepKey(int64_t nIndex);
974 void ReturnKey(int64_t nIndex);
975 bool GetKeyFromPool(CPubKey &key, bool internal = false);
976 int64_t GetOldestKeyPoolTime();
977 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
979 std::set< std::set<CTxDestination> > GetAddressGroupings();
980 std::map<CTxDestination, CAmount> GetAddressBalances();
982 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
984 isminetype IsMine(const CTxIn& txin) const;
986 * Returns amount of debit if the input matches the
987 * filter, otherwise returns 0
989 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
990 isminetype IsMine(const CTxOut& txout) const;
991 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
992 bool IsChange(const CTxOut& txout) const;
993 CAmount GetChange(const CTxOut& txout) const;
994 bool IsMine(const CTransaction& tx) const;
995 /** should probably be renamed to IsRelevantToMe */
996 bool IsFromMe(const CTransaction& tx) const;
997 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
998 /** Returns whether all of the inputs match the filter */
999 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1000 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1001 CAmount GetChange(const CTransaction& tx) const;
1002 void SetBestChain(const CBlockLocator& loc) override;
1004 DBErrors LoadWallet(bool& fFirstRunRet);
1005 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1006 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1008 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1010 bool DelAddressBook(const CTxDestination& address);
1012 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1014 void Inventory(const uint256 &hash) override
1017 LOCK(cs_wallet);
1018 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1019 if (mi != mapRequestCount.end())
1020 (*mi).second++;
1024 void GetScriptForMining(std::shared_ptr<CReserveScript> &script) override;
1026 unsigned int GetKeyPoolSize()
1028 AssertLockHeld(cs_wallet); // setKeyPool
1029 return setKeyPool.size();
1032 bool SetDefaultKey(const CPubKey &vchPubKey);
1034 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1035 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
1037 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1038 bool SetMaxVersion(int nVersion);
1040 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1041 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1043 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1044 std::set<uint256> GetConflicts(const uint256& txid) const;
1046 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1047 bool HasWalletSpend(const uint256& txid) const;
1049 //! Flush wallet (bitdb flush)
1050 void Flush(bool shutdown=false);
1052 //! Verify the wallet database and perform salvage if required
1053 static bool Verify();
1055 /**
1056 * Address book entry changed.
1057 * @note called with lock cs_wallet held.
1059 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1060 &address, const std::string &label, bool isMine,
1061 const std::string &purpose,
1062 ChangeType status)> NotifyAddressBookChanged;
1064 /**
1065 * Wallet transaction added, removed or updated.
1066 * @note called with lock cs_wallet held.
1068 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1069 ChangeType status)> NotifyTransactionChanged;
1071 /** Show progress e.g. for rescan */
1072 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1074 /** Watch-only address added */
1075 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1077 /** Inquire whether this wallet broadcasts transactions. */
1078 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1079 /** Set whether this wallet broadcasts transactions. */
1080 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1082 /** Return whether transaction can be abandoned */
1083 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1085 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1086 bool AbandonTransaction(const uint256& hashTx);
1088 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1089 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1091 /* Returns the wallets help message */
1092 static std::string GetWalletHelpString(bool showDebug);
1094 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1095 static CWallet* CreateWalletFromFile(const std::string walletFile);
1096 static bool InitLoadWallet();
1099 * Wallet post-init setup
1100 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1102 void postInitProcess(CScheduler& scheduler);
1104 /* Wallets parameter interaction */
1105 static bool ParameterInteraction();
1107 bool BackupWallet(const std::string& strDest);
1109 /* Set the HD chain model (chain child index counters) */
1110 bool SetHDChain(const CHDChain& chain, bool memonly);
1111 const CHDChain& GetHDChain() const { return hdChain; }
1113 /* Returns true if HD is enabled */
1114 bool IsHDEnabled() const;
1116 /* Generates a new HD master key (will not be activated) */
1117 CPubKey GenerateNewHDMasterKey();
1119 /* Set the current HD master key (will reset the chain child index counters)
1120 Sets the master key's version based on the current wallet version (so the
1121 caller must ensure the current wallet version is correct before calling
1122 this function). */
1123 bool SetHDMasterKey(const CPubKey& key);
1126 /** A key allocated from the key pool. */
1127 class CReserveKey : public CReserveScript
1129 protected:
1130 CWallet* pwallet;
1131 int64_t nIndex;
1132 CPubKey vchPubKey;
1133 public:
1134 CReserveKey(CWallet* pwalletIn)
1136 nIndex = -1;
1137 pwallet = pwalletIn;
1140 CReserveKey() = default;
1141 CReserveKey(const CReserveKey&) = delete;
1142 CReserveKey& operator=(const CReserveKey&) = delete;
1144 ~CReserveKey()
1146 ReturnKey();
1149 void ReturnKey();
1150 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1151 void KeepKey();
1152 void KeepScript() { KeepKey(); }
1156 /**
1157 * Account information.
1158 * Stored in wallet with key "acc"+string account name.
1160 class CAccount
1162 public:
1163 CPubKey vchPubKey;
1165 CAccount()
1167 SetNull();
1170 void SetNull()
1172 vchPubKey = CPubKey();
1175 ADD_SERIALIZE_METHODS;
1177 template <typename Stream, typename Operation>
1178 inline void SerializationOp(Stream& s, Operation ser_action) {
1179 int nVersion = s.GetVersion();
1180 if (!(s.GetType() & SER_GETHASH))
1181 READWRITE(nVersion);
1182 READWRITE(vchPubKey);
1186 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1187 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1188 // so that each entry corresponds to each vIn, in order.
1189 template <typename ContainerType>
1190 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1192 // Fill in dummy signatures for fee calculation.
1193 int nIn = 0;
1194 for (const auto& coin : coins)
1196 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1197 SignatureData sigdata;
1199 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1201 return false;
1202 } else {
1203 UpdateTransaction(txNew, nIn, sigdata);
1206 nIn++;
1208 return true;
1210 #endif // BITCOIN_WALLET_WALLET_H