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
10 #include <policy/feerate.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>
32 typedef CWallet
* CWalletRef
;
33 extern std::vector
<CWalletRef
> vpwallets
;
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;
45 static const CAmount DEFAULT_TRANSACTION_FEE
= 0;
46 //! -fallbackfee default
47 static const CAmount DEFAULT_FALLBACK_FEE
= 20000;
48 //! -m_discard_rate default
49 static const CAmount DEFAULT_DISCARD_FEE
= 10000;
51 static const CAmount DEFAULT_TRANSACTION_MINFEE
= 1000;
52 //! minimum recommended increment for BIP 125 replacement txs
53 static const CAmount WALLET_INCREMENTAL_RELAY_FEE
= 5000;
54 //! target minimum change amount
55 static const CAmount MIN_CHANGE
= CENT
;
56 //! final minimum change amount after paying for fees
57 static const CAmount MIN_FINAL_CHANGE
= MIN_CHANGE
/2;
58 //! Default for -spendzeroconfchange
59 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
= true;
60 //! Default for -walletrejectlongchains
61 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
= false;
62 //! -txconfirmtarget default
63 static const unsigned int DEFAULT_TX_CONFIRM_TARGET
= 6;
64 //! -walletrbf default
65 static const bool DEFAULT_WALLET_RBF
= false;
66 static const bool DEFAULT_WALLETBROADCAST
= true;
67 static const bool DEFAULT_DISABLE_WALLET
= false;
69 extern const char * DEFAULT_WALLET_DAT
;
71 static const int64_t TIMESTAMP_MIN
= 0;
80 class CBlockPolicyEstimator
;
82 struct FeeCalculation
;
83 enum class FeeEstimateMode
;
85 /** (client) version numbers for particular wallet features */
88 FEATURE_BASE
= 10500, // the earliest version new wallets supports (only useful for getwalletinfo'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_NO_DEFAULT_KEY
= 159900, // Wallet without a default key written
99 FEATURE_LATEST
= FEATURE_COMPRPUBKEY
// HD is optional, use FEATURE_COMPRPUBKEY as latest version
103 /** A key pool entry */
109 bool fInternal
; // for change outputs
112 CKeyPool(const CPubKey
& vchPubKeyIn
, bool internalIn
);
114 ADD_SERIALIZE_METHODS
;
116 template <typename Stream
, typename Operation
>
117 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
118 int nVersion
= s
.GetVersion();
119 if (!(s
.GetType() & SER_GETHASH
))
122 READWRITE(vchPubKey
);
123 if (ser_action
.ForRead()) {
125 READWRITE(fInternal
);
127 catch (std::ios_base::failure
&) {
128 /* flag as external address if we can't read the internal boolean
129 (this will be the case for any wallet before the HD chain split version) */
134 READWRITE(fInternal
);
139 /** Address book data */
140 class CAddressBookData
146 CAddressBookData() : purpose("unknown") {}
148 typedef std::map
<std::string
, std::string
> StringMap
;
154 CScript scriptPubKey
;
156 bool fSubtractFeeFromAmount
;
159 typedef std::map
<std::string
, std::string
> mapValue_t
;
162 static inline void ReadOrderPos(int64_t& nOrderPos
, mapValue_t
& mapValue
)
164 if (!mapValue
.count("n"))
166 nOrderPos
= -1; // TODO: calculate elsewhere
169 nOrderPos
= atoi64(mapValue
["n"].c_str());
173 static inline void WriteOrderPos(const int64_t& nOrderPos
, mapValue_t
& mapValue
)
177 mapValue
["n"] = i64tostr(nOrderPos
);
182 CTxDestination destination
;
187 /** A transaction with a merkle branch linking it to the block chain. */
191 /** Constant used in hashBlock to indicate tx has been abandoned */
192 static const uint256 ABANDON_HASH
;
198 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
199 * block in the chain we know this or any in-wallet dependency conflicts
200 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
207 SetTx(MakeTransactionRef());
211 explicit CMerkleTx(CTransactionRef arg
)
213 SetTx(std::move(arg
));
219 hashBlock
= uint256();
223 void SetTx(CTransactionRef arg
)
228 ADD_SERIALIZE_METHODS
;
230 template <typename Stream
, typename Operation
>
231 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
232 std::vector
<uint256
> vMerkleBranch
; // For compatibility with older versions.
234 READWRITE(hashBlock
);
235 READWRITE(vMerkleBranch
);
239 void SetMerkleBranch(const CBlockIndex
* pIndex
, int posInBlock
);
242 * Return depth of transaction in blockchain:
243 * <0 : conflicts with a transaction this deep in the blockchain
244 * 0 : in memory pool, waiting to be included in a block
245 * >=1 : this many blocks deep in the main chain
247 int GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const;
248 int GetDepthInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
); }
249 bool IsInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
) > 0; }
250 int GetBlocksToMaturity() const;
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(); }
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
266 const CWallet
* pwallet
;
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)
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.
314 std::string strFromAccount
;
315 int64_t nOrderPos
; //!< position in ordered transaction list
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 bool fInMempool
;
328 mutable CAmount nDebitCached
;
329 mutable CAmount nCreditCached
;
330 mutable CAmount nImmatureCreditCached
;
331 mutable CAmount nAvailableCreditCached
;
332 mutable CAmount nWatchDebitCached
;
333 mutable CAmount nWatchCreditCached
;
334 mutable CAmount nImmatureWatchCreditCached
;
335 mutable CAmount nAvailableWatchCreditCached
;
336 mutable CAmount nChangeCached
;
343 CWalletTx(const CWallet
* pwalletIn
, CTransactionRef arg
) : CMerkleTx(std::move(arg
))
348 void Init(const CWallet
* pwalletIn
)
353 fTimeReceivedIsTxTime
= false;
357 strFromAccount
.clear();
358 fDebitCached
= false;
359 fCreditCached
= false;
360 fImmatureCreditCached
= false;
361 fAvailableCreditCached
= false;
362 fWatchDebitCached
= false;
363 fWatchCreditCached
= false;
364 fImmatureWatchCreditCached
= false;
365 fAvailableWatchCreditCached
= false;
366 fChangeCached
= false;
370 nImmatureCreditCached
= 0;
371 nAvailableCreditCached
= 0;
372 nWatchDebitCached
= 0;
373 nWatchCreditCached
= 0;
374 nAvailableWatchCreditCached
= 0;
375 nImmatureWatchCreditCached
= 0;
380 ADD_SERIALIZE_METHODS
;
382 template <typename Stream
, typename Operation
>
383 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
384 if (ser_action
.ForRead())
388 if (!ser_action
.ForRead())
390 mapValue
["fromaccount"] = strFromAccount
;
392 WriteOrderPos(nOrderPos
, mapValue
);
395 mapValue
["timesmart"] = strprintf("%u", nTimeSmart
);
398 READWRITE(*(CMerkleTx
*)this);
399 std::vector
<CMerkleTx
> vUnused
; //!< Used to be vtxPrev
402 READWRITE(vOrderForm
);
403 READWRITE(fTimeReceivedIsTxTime
);
404 READWRITE(nTimeReceived
);
408 if (ser_action
.ForRead())
410 strFromAccount
= mapValue
["fromaccount"];
412 ReadOrderPos(nOrderPos
, mapValue
);
414 nTimeSmart
= mapValue
.count("timesmart") ? (unsigned int)atoi64(mapValue
["timesmart"]) : 0;
417 mapValue
.erase("fromaccount");
418 mapValue
.erase("spent");
420 mapValue
.erase("timesmart");
423 //! make sure balances are recalculated
426 fCreditCached
= false;
427 fAvailableCreditCached
= false;
428 fImmatureCreditCached
= false;
429 fWatchDebitCached
= false;
430 fWatchCreditCached
= false;
431 fAvailableWatchCreditCached
= false;
432 fImmatureWatchCreditCached
= false;
433 fDebitCached
= false;
434 fChangeCached
= false;
437 void BindWallet(CWallet
*pwalletIn
)
443 //! filter decides which addresses will count towards the debit
444 CAmount
GetDebit(const isminefilter
& filter
) const;
445 CAmount
GetCredit(const isminefilter
& filter
) const;
446 CAmount
GetImmatureCredit(bool fUseCache
=true) const;
447 CAmount
GetAvailableCredit(bool fUseCache
=true) const;
448 CAmount
GetImmatureWatchOnlyCredit(const bool& fUseCache
=true) const;
449 CAmount
GetAvailableWatchOnlyCredit(const bool& fUseCache
=true) const;
450 CAmount
GetChange() const;
452 void GetAmounts(std::list
<COutputEntry
>& listReceived
,
453 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const;
455 bool IsFromMe(const isminefilter
& filter
) const
457 return (GetDebit(filter
) > 0);
460 // True if only scriptSigs are different
461 bool IsEquivalentTo(const CWalletTx
& tx
) const;
463 bool InMempool() const;
464 bool IsTrusted() const;
466 int64_t GetTxTime() const;
467 int GetRequestCount() const;
469 // RelayWalletTransaction may only be called if fBroadcastTransactions!
470 bool RelayWalletTransaction(CConnman
* connman
);
472 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
473 bool AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
);
475 std::set
<uint256
> GetConflicts() const;
481 CInputCoin(const CWalletTx
* walletTx
, unsigned int i
)
484 throw std::invalid_argument("walletTx should not be null");
485 if (i
>= walletTx
->tx
->vout
.size())
486 throw std::out_of_range("The output index is out of range");
488 outpoint
= COutPoint(walletTx
->GetHash(), i
);
489 txout
= walletTx
->tx
->vout
[i
];
495 bool operator<(const CInputCoin
& rhs
) const {
496 return outpoint
< rhs
.outpoint
;
499 bool operator!=(const CInputCoin
& rhs
) const {
500 return outpoint
!= rhs
.outpoint
;
503 bool operator==(const CInputCoin
& rhs
) const {
504 return outpoint
== rhs
.outpoint
;
515 /** Whether we have the private keys to spend this output */
518 /** Whether we know how to spend this output, ignoring the lack of keys */
522 * Whether this output is considered safe to spend. Unconfirmed transactions
523 * from outside keys and unconfirmed replacement transactions are considered
524 * unsafe and will not be used to fund new spending transactions.
528 COutput(const CWalletTx
*txIn
, int iIn
, int nDepthIn
, bool fSpendableIn
, bool fSolvableIn
, bool fSafeIn
)
530 tx
= txIn
; i
= iIn
; nDepth
= nDepthIn
; fSpendable
= fSpendableIn
; fSolvable
= fSolvableIn
; fSafe
= fSafeIn
;
533 std::string
ToString() const;
539 /** Private key that includes an expiration date in case it never gets used. */
544 int64_t nTimeCreated
;
545 int64_t nTimeExpires
;
546 std::string strComment
;
547 //! todo: add something to note what created it (user, getnewaddress, change)
548 //! maybe should have a map<string, string> property map
550 explicit CWalletKey(int64_t nExpires
=0);
552 ADD_SERIALIZE_METHODS
;
554 template <typename Stream
, typename Operation
>
555 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
556 int nVersion
= s
.GetVersion();
557 if (!(s
.GetType() & SER_GETHASH
))
559 READWRITE(vchPrivKey
);
560 READWRITE(nTimeCreated
);
561 READWRITE(nTimeExpires
);
562 READWRITE(LIMITED_STRING(strComment
, 65536));
567 * Internal transfers.
568 * Database key is acentry<account><counter>.
570 class CAccountingEntry
573 std::string strAccount
;
574 CAmount nCreditDebit
;
576 std::string strOtherAccount
;
577 std::string strComment
;
579 int64_t nOrderPos
; //!< position in ordered transaction list
592 strOtherAccount
.clear();
598 ADD_SERIALIZE_METHODS
;
600 template <typename Stream
, typename Operation
>
601 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
602 int nVersion
= s
.GetVersion();
603 if (!(s
.GetType() & SER_GETHASH
))
605 //! Note: strAccount is serialized as part of the key, not here.
606 READWRITE(nCreditDebit
);
608 READWRITE(LIMITED_STRING(strOtherAccount
, 65536));
610 if (!ser_action
.ForRead())
612 WriteOrderPos(nOrderPos
, mapValue
);
614 if (!(mapValue
.empty() && _ssExtra
.empty()))
616 CDataStream
ss(s
.GetType(), s
.GetVersion());
617 ss
.insert(ss
.begin(), '\0');
619 ss
.insert(ss
.end(), _ssExtra
.begin(), _ssExtra
.end());
620 strComment
.append(ss
.str());
624 READWRITE(LIMITED_STRING(strComment
, 65536));
626 size_t nSepPos
= strComment
.find("\0", 0, 1);
627 if (ser_action
.ForRead())
630 if (std::string::npos
!= nSepPos
)
632 CDataStream
ss(std::vector
<char>(strComment
.begin() + nSepPos
+ 1, strComment
.end()), s
.GetType(), s
.GetVersion());
634 _ssExtra
= std::vector
<char>(ss
.begin(), ss
.end());
636 ReadOrderPos(nOrderPos
, mapValue
);
638 if (std::string::npos
!= nSepPos
)
639 strComment
.erase(nSepPos
);
645 std::vector
<char> _ssExtra
;
650 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
651 * and provides the ability to create new transactions.
653 class CWallet final
: public CCryptoKeyStore
, public CValidationInterface
656 static std::atomic
<bool> fFlushScheduled
;
657 std::atomic
<bool> fAbortRescan
;
658 std::atomic
<bool> fScanningWallet
;
661 * Select a set of coins such that nValueRet >= nTargetValue and at least
662 * all coins from coinControl are selected; Never select unconfirmed coins
663 * if they are not ours
665 bool SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
*coinControl
= nullptr) const;
667 CWalletDB
*pwalletdbEncryption
;
669 //! the current wallet version: clients below this version are not able to load the wallet
672 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
673 int nWalletMaxVersion
;
677 bool fBroadcastTransactions
;
680 * Used to keep track of spent outpoints, and
681 * detect and report conflicts (double-spends or
682 * mutated transactions where the mutant gets mined).
684 typedef std::multimap
<COutPoint
, uint256
> TxSpends
;
685 TxSpends mapTxSpends
;
686 void AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
);
687 void AddToSpends(const uint256
& wtxid
);
689 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
690 void MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
);
692 void SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
>);
694 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
695 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
696 void SyncTransaction(const CTransactionRef
& tx
, const CBlockIndex
*pindex
= nullptr, int posInBlock
= 0);
698 /* the HD chain data model (external chain counters) */
701 /* HD derive new child key (on internal or external chain) */
702 void DeriveNewChildKey(CWalletDB
&walletdb
, CKeyMetadata
& metadata
, CKey
& secret
, bool internal
= false);
704 std::set
<int64_t> setInternalKeyPool
;
705 std::set
<int64_t> setExternalKeyPool
;
706 int64_t m_max_keypool_index
;
707 std::map
<CKeyID
, int64_t> m_pool_key_to_index
;
709 int64_t nTimeFirstKey
;
712 * Private version of AddWatchOnly method which does not accept a
713 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
714 * the watch key did not previously have a timestamp associated with it.
715 * Because this is an inherited virtual method, it is accessible despite
716 * being marked private, but it is marked private anyway to encourage use
717 * of the other AddWatchOnly which accepts a timestamp and sets
718 * nTimeFirstKey more intelligently for more efficient rescans.
720 bool AddWatchOnly(const CScript
& dest
) override
;
722 std::unique_ptr
<CWalletDBWrapper
> dbw
;
725 * The following is used to keep track of how far behind the wallet is
726 * from the chain sync, and to allow clients to block on us being caught up.
728 * Note that this is *not* how far we've processed, we may need some rescan
729 * to have seen all transactions in the chain, but is only used to track
730 * live BlockConnected callbacks.
732 * Protected by cs_main (see BlockUntilSyncedToCurrentChain)
734 const CBlockIndex
* m_last_block_processed
;
739 * This lock protects all the fields added by CWallet.
741 mutable CCriticalSection cs_wallet
;
743 /** Get database handle used by this wallet. Ideally this function would
746 CWalletDBWrapper
& GetDBHandle()
751 /** Get a name for this wallet for logging/debugging purposes.
753 std::string
GetName() const
756 return dbw
->GetName();
762 void LoadKeyPool(int64_t nIndex
, const CKeyPool
&keypool
);
764 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
766 std::map
<CTxDestination
, CKeyMetadata
> mapKeyMetadata
;
768 typedef std::map
<unsigned int, CMasterKey
> MasterKeyMap
;
769 MasterKeyMap mapMasterKeys
;
770 unsigned int nMasterKeyMaxID
;
772 // Create wallet with dummy database handle
773 CWallet(): dbw(new CWalletDBWrapper())
778 // Create wallet with passed-in database handle
779 explicit CWallet(std::unique_ptr
<CWalletDBWrapper
> dbw_in
) : dbw(std::move(dbw_in
))
786 delete pwalletdbEncryption
;
787 pwalletdbEncryption
= nullptr;
792 nWalletVersion
= FEATURE_BASE
;
793 nWalletMaxVersion
= FEATURE_BASE
;
795 pwalletdbEncryption
= nullptr;
797 nAccountingEntryNumber
= 0;
800 m_max_keypool_index
= 0;
802 fBroadcastTransactions
= false;
804 fAbortRescan
= false;
805 fScanningWallet
= false;
808 std::map
<uint256
, CWalletTx
> mapWallet
;
809 std::list
<CAccountingEntry
> laccentries
;
811 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
812 typedef std::multimap
<int64_t, TxPair
> TxItems
;
815 int64_t nOrderPosNext
;
816 uint64_t nAccountingEntryNumber
;
817 std::map
<uint256
, int> mapRequestCount
;
819 std::map
<CTxDestination
, CAddressBookData
> mapAddressBook
;
821 std::set
<COutPoint
> setLockedCoins
;
823 const CWalletTx
* GetWalletTx(const uint256
& hash
) const;
825 //! check whether we are allowed to upgrade (or already support) to the named feature
826 bool CanSupportFeature(enum WalletFeature wf
) const { AssertLockHeld(cs_wallet
); return nWalletMaxVersion
>= wf
; }
829 * populate vCoins with vector of available COutputs.
831 void AvailableCoins(std::vector
<COutput
>& vCoins
, bool fOnlySafe
=true, const CCoinControl
*coinControl
= nullptr, 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;
834 * Return list of available coins and locked coins grouped by non-change output address.
836 std::map
<CTxDestination
, std::vector
<COutput
>> ListCoins() const;
839 * Find non-change parent output.
841 const CTxOut
& FindNonChangeParentOutput(const CTransaction
& tx
, int output
) const;
844 * Shuffle and select coins until nTargetValue is reached while avoiding
845 * small change; This method is stochastic for some inputs and upon
846 * completion the coin set and corresponding actual target value is
849 bool SelectCoinsMinConf(const CAmount
& nTargetValue
, int nConfMine
, int nConfTheirs
, uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
) const;
851 bool IsSpent(const uint256
& hash
, unsigned int n
) const;
853 bool IsLockedCoin(uint256 hash
, unsigned int n
) const;
854 void LockCoin(const COutPoint
& output
);
855 void UnlockCoin(const COutPoint
& output
);
856 void UnlockAllCoins();
857 void ListLockedCoins(std::vector
<COutPoint
>& vOutpts
) const;
860 * Rescan abort properties
862 void AbortRescan() { fAbortRescan
= true; }
863 bool IsAbortingRescan() { return fAbortRescan
; }
864 bool IsScanning() { return fScanningWallet
; }
867 * keystore implementation
870 CPubKey
GenerateNewKey(CWalletDB
& walletdb
, bool internal
= false);
871 //! Adds a key to the store, and saves it to disk.
872 bool AddKeyPubKey(const CKey
& key
, const CPubKey
&pubkey
) override
;
873 bool AddKeyPubKeyWithDB(CWalletDB
&walletdb
,const CKey
& key
, const CPubKey
&pubkey
);
874 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
875 bool LoadKey(const CKey
& key
, const CPubKey
&pubkey
) { return CCryptoKeyStore::AddKeyPubKey(key
, pubkey
); }
876 //! Load metadata (used by LoadWallet)
877 bool LoadKeyMetadata(const CTxDestination
& pubKey
, const CKeyMetadata
&metadata
);
879 bool LoadMinVersion(int nVersion
) { AssertLockHeld(cs_wallet
); nWalletVersion
= nVersion
; nWalletMaxVersion
= std::max(nWalletMaxVersion
, nVersion
); return true; }
880 void UpdateTimeFirstKey(int64_t nCreateTime
);
882 //! Adds an encrypted key to the store, and saves it to disk.
883 bool AddCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
) override
;
884 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
885 bool LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
);
886 bool AddCScript(const CScript
& redeemScript
) override
;
887 bool LoadCScript(const CScript
& redeemScript
);
889 //! Adds a destination data tuple to the store, and saves it to disk
890 bool AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
891 //! Erases a destination data tuple in the store and on disk
892 bool EraseDestData(const CTxDestination
&dest
, const std::string
&key
);
893 //! Adds a destination data tuple to the store, without saving it to disk
894 bool LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
895 //! Look up a destination data tuple in the store, return true if found false otherwise
896 bool GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const;
897 //! Get all destination values matching a prefix.
898 std::vector
<std::string
> GetDestValues(const std::string
& prefix
) const;
900 //! Adds a watch-only address to the store, and saves it to disk.
901 bool AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
);
902 bool RemoveWatchOnly(const CScript
&dest
) override
;
903 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
904 bool LoadWatchOnly(const CScript
&dest
);
906 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
909 bool Unlock(const SecureString
& strWalletPassphrase
);
910 bool ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
);
911 bool EncryptWallet(const SecureString
& strWalletPassphrase
);
913 void GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const;
914 unsigned int ComputeTimeSmart(const CWalletTx
& wtx
) const;
917 * Increment the next transaction order id
918 * @return next transaction order id
920 int64_t IncOrderPosNext(CWalletDB
*pwalletdb
= nullptr);
921 DBErrors
ReorderTransactions();
922 bool AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
= "");
923 bool GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
= false);
926 bool AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
=true);
927 bool LoadToWallet(const CWalletTx
& wtxIn
);
928 void TransactionAddedToMempool(const CTransactionRef
& tx
) override
;
929 void BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
*pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) override
;
930 void BlockDisconnected(const std::shared_ptr
<const CBlock
>& pblock
) override
;
931 bool AddToWalletIfInvolvingMe(const CTransactionRef
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
);
932 int64_t RescanFromTime(int64_t startTime
, bool update
);
933 CBlockIndex
* ScanForWalletTransactions(CBlockIndex
* pindexStart
, CBlockIndex
* pindexStop
, bool fUpdate
= false);
934 void TransactionRemovedFromMempool(const CTransactionRef
&ptx
) override
;
935 void ReacceptWalletTransactions();
936 void ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
) override
;
937 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
938 std::vector
<uint256
> ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
);
939 CAmount
GetBalance() const;
940 CAmount
GetUnconfirmedBalance() const;
941 CAmount
GetImmatureBalance() const;
942 CAmount
GetWatchOnlyBalance() const;
943 CAmount
GetUnconfirmedWatchOnlyBalance() const;
944 CAmount
GetImmatureWatchOnlyBalance() const;
945 CAmount
GetLegacyBalance(const isminefilter
& filter
, int minDepth
, const std::string
* account
) const;
946 CAmount
GetAvailableBalance(const CCoinControl
* coinControl
= nullptr) const;
949 * Insert additional inputs into the transaction by
950 * calling CreateTransaction();
952 bool FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, int& nChangePosInOut
, std::string
& strFailReason
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, CCoinControl
);
953 bool SignTransaction(CMutableTransaction
& tx
);
956 * Create a new transaction paying the recipients with a set of coins
957 * selected by SelectCoins(); Also create the change output, when needed
958 * @note passing nChangePosInOut as -1 will result in setting a random position
960 bool CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
, int& nChangePosInOut
,
961 std::string
& strFailReason
, const CCoinControl
& coin_control
, bool sign
= true);
962 bool CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
);
964 void ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
);
965 bool AddAccountingEntry(const CAccountingEntry
&);
966 bool AddAccountingEntry(const CAccountingEntry
&, CWalletDB
*pwalletdb
);
967 template <typename ContainerType
>
968 bool DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
) const;
970 static CFeeRate minTxFee
;
971 static CFeeRate fallbackFee
;
972 static CFeeRate m_discard_rate
;
975 size_t KeypoolCountExternalKeys();
976 bool TopUpKeyPool(unsigned int kpSize
= 0);
977 void ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
, bool fRequestedInternal
);
978 void KeepKey(int64_t nIndex
);
979 void ReturnKey(int64_t nIndex
, bool fInternal
, const CPubKey
& pubkey
);
980 bool GetKeyFromPool(CPubKey
&key
, bool internal
= false);
981 int64_t GetOldestKeyPoolTime();
983 * Marks all keys in the keypool up to and including reserve_key as used.
985 void MarkReserveKeysAsUsed(int64_t keypool_id
);
986 const std::map
<CKeyID
, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index
; }
988 std::set
< std::set
<CTxDestination
> > GetAddressGroupings();
989 std::map
<CTxDestination
, CAmount
> GetAddressBalances();
991 std::set
<CTxDestination
> GetAccountAddresses(const std::string
& strAccount
) const;
993 isminetype
IsMine(const CTxIn
& txin
) const;
995 * Returns amount of debit if the input matches the
996 * filter, otherwise returns 0
998 CAmount
GetDebit(const CTxIn
& txin
, const isminefilter
& filter
) const;
999 isminetype
IsMine(const CTxOut
& txout
) const;
1000 CAmount
GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const;
1001 bool IsChange(const CTxOut
& txout
) const;
1002 CAmount
GetChange(const CTxOut
& txout
) const;
1003 bool IsMine(const CTransaction
& tx
) const;
1004 /** should probably be renamed to IsRelevantToMe */
1005 bool IsFromMe(const CTransaction
& tx
) const;
1006 CAmount
GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const;
1007 /** Returns whether all of the inputs match the filter */
1008 bool IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const;
1009 CAmount
GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const;
1010 CAmount
GetChange(const CTransaction
& tx
) const;
1011 void SetBestChain(const CBlockLocator
& loc
) override
;
1013 DBErrors
LoadWallet(bool& fFirstRunRet
);
1014 DBErrors
ZapWalletTx(std::vector
<CWalletTx
>& vWtx
);
1015 DBErrors
ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
);
1017 bool SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& purpose
);
1019 bool DelAddressBook(const CTxDestination
& address
);
1021 const std::string
& GetAccountName(const CScript
& scriptPubKey
) const;
1023 void Inventory(const uint256
&hash
) override
1027 std::map
<uint256
, int>::iterator mi
= mapRequestCount
.find(hash
);
1028 if (mi
!= mapRequestCount
.end())
1033 void GetScriptForMining(std::shared_ptr
<CReserveScript
> &script
);
1035 unsigned int GetKeyPoolSize()
1037 AssertLockHeld(cs_wallet
); // set{Ex,In}ternalKeyPool
1038 return setInternalKeyPool
.size() + setExternalKeyPool
.size();
1041 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1042 bool SetMinVersion(enum WalletFeature
, CWalletDB
* pwalletdbIn
= nullptr, bool fExplicit
= false);
1044 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1045 bool SetMaxVersion(int nVersion
);
1047 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1048 int GetVersion() { LOCK(cs_wallet
); return nWalletVersion
; }
1050 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1051 std::set
<uint256
> GetConflicts(const uint256
& txid
) const;
1053 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1054 bool HasWalletSpend(const uint256
& txid
) const;
1056 //! Flush wallet (bitdb flush)
1057 void Flush(bool shutdown
=false);
1060 * Address book entry changed.
1061 * @note called with lock cs_wallet held.
1063 boost::signals2::signal
<void (CWallet
*wallet
, const CTxDestination
1064 &address
, const std::string
&label
, bool isMine
,
1065 const std::string
&purpose
,
1066 ChangeType status
)> NotifyAddressBookChanged
;
1069 * Wallet transaction added, removed or updated.
1070 * @note called with lock cs_wallet held.
1072 boost::signals2::signal
<void (CWallet
*wallet
, const uint256
&hashTx
,
1073 ChangeType status
)> NotifyTransactionChanged
;
1075 /** Show progress e.g. for rescan */
1076 boost::signals2::signal
<void (const std::string
&title
, int nProgress
)> ShowProgress
;
1078 /** Watch-only address added */
1079 boost::signals2::signal
<void (bool fHaveWatchOnly
)> NotifyWatchonlyChanged
;
1081 /** Inquire whether this wallet broadcasts transactions. */
1082 bool GetBroadcastTransactions() const { return fBroadcastTransactions
; }
1083 /** Set whether this wallet broadcasts transactions. */
1084 void SetBroadcastTransactions(bool broadcast
) { fBroadcastTransactions
= broadcast
; }
1086 /** Return whether transaction can be abandoned */
1087 bool TransactionCanBeAbandoned(const uint256
& hashTx
) const;
1089 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1090 bool AbandonTransaction(const uint256
& hashTx
);
1092 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1093 bool MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
);
1095 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1096 static CWallet
* CreateWalletFromFile(const std::string walletFile
);
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 bool BackupWallet(const std::string
& strDest
);
1106 /* Set the HD chain model (chain child index counters) */
1107 bool SetHDChain(const CHDChain
& chain
, bool memonly
);
1108 const CHDChain
& GetHDChain() const { return hdChain
; }
1110 /* Returns true if HD is enabled */
1111 bool IsHDEnabled() const;
1113 /* Generates a new HD master key (will not be activated) */
1114 CPubKey
GenerateNewHDMasterKey();
1116 /* Set the current HD master key (will reset the chain child index counters)
1117 Sets the master key's version based on the current wallet version (so the
1118 caller must ensure the current wallet version is correct before calling
1120 bool SetHDMasterKey(const CPubKey
& key
);
1123 * Blocks until the wallet state is up-to-date to /at least/ the current
1124 * chain at the time this function is entered
1125 * Obviously holding cs_main/cs_wallet when going into this call may cause
1128 void BlockUntilSyncedToCurrentChain();
1131 /** A key allocated from the key pool. */
1132 class CReserveKey final
: public CReserveScript
1140 explicit CReserveKey(CWallet
* pwalletIn
)
1143 pwallet
= pwalletIn
;
1147 CReserveKey() = default;
1148 CReserveKey(const CReserveKey
&) = delete;
1149 CReserveKey
& operator=(const CReserveKey
&) = delete;
1157 bool GetReservedKey(CPubKey
&pubkey
, bool internal
= false);
1159 void KeepScript() override
{ KeepKey(); }
1164 * Account information.
1165 * Stored in wallet with key "acc"+string account name.
1179 vchPubKey
= CPubKey();
1182 ADD_SERIALIZE_METHODS
;
1184 template <typename Stream
, typename Operation
>
1185 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
1186 int nVersion
= s
.GetVersion();
1187 if (!(s
.GetType() & SER_GETHASH
))
1188 READWRITE(nVersion
);
1189 READWRITE(vchPubKey
);
1193 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1194 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1195 // so that each entry corresponds to each vIn, in order.
1196 template <typename ContainerType
>
1197 bool CWallet::DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
) const
1199 // Fill in dummy signatures for fee calculation.
1201 for (const auto& coin
: coins
)
1203 const CScript
& scriptPubKey
= coin
.txout
.scriptPubKey
;
1204 SignatureData sigdata
;
1206 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey
, sigdata
))
1210 UpdateTransaction(txNew
, nIn
, sigdata
);
1218 #endif // BITCOIN_WALLET_WALLET_H