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;
68 //! if set, all keys will be derived by using BIP32
69 static const bool DEFAULT_USE_HD_WALLET
= true;
71 extern const char * DEFAULT_WALLET_DAT
;
73 static const int64_t TIMESTAMP_MIN
= 0;
82 class CBlockPolicyEstimator
;
84 struct FeeCalculation
;
85 enum class FeeEstimateMode
;
87 /** (client) version numbers for particular wallet features */
90 FEATURE_BASE
= 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
92 FEATURE_WALLETCRYPT
= 40000, // wallet encryption
93 FEATURE_COMPRPUBKEY
= 60000, // compressed public keys
95 FEATURE_HD
= 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
97 FEATURE_HD_SPLIT
= 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
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
));
217 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
218 * TODO: adapt callers and remove this operator. */
219 operator const CTransaction
&() const { return *tx
; }
223 hashBlock
= uint256();
227 void SetTx(CTransactionRef arg
)
232 ADD_SERIALIZE_METHODS
;
234 template <typename Stream
, typename Operation
>
235 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
236 std::vector
<uint256
> vMerkleBranch
; // For compatibility with older versions.
238 READWRITE(hashBlock
);
239 READWRITE(vMerkleBranch
);
243 void SetMerkleBranch(const CBlockIndex
* pIndex
, int posInBlock
);
246 * Return depth of transaction in blockchain:
247 * <0 : conflicts with a transaction this deep in the blockchain
248 * 0 : in memory pool, waiting to be included in a block
249 * >=1 : this many blocks deep in the main chain
251 int GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const;
252 int GetDepthInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
); }
253 bool IsInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
) > 0; }
254 int GetBlocksToMaturity() const;
255 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
256 bool AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
);
257 bool hashUnset() const { return (hashBlock
.IsNull() || hashBlock
== ABANDON_HASH
); }
258 bool isAbandoned() const { return (hashBlock
== ABANDON_HASH
); }
259 void setAbandoned() { hashBlock
= ABANDON_HASH
; }
261 const uint256
& GetHash() const { return tx
->GetHash(); }
262 bool IsCoinBase() const { return tx
->IsCoinBase(); }
266 * A transaction with a bunch of additional info that only the owner cares about.
267 * It includes any unrecorded transactions needed to link it back to the block chain.
269 class CWalletTx
: public CMerkleTx
272 const CWallet
* pwallet
;
276 * Key/value map with information about the transaction.
278 * The following keys can be read and written through the map and are
279 * serialized in the wallet database:
281 * "comment", "to" - comment strings provided to sendtoaddress,
282 * sendfrom, sendmany wallet RPCs
283 * "replaces_txid" - txid (as HexStr) of transaction replaced by
284 * bumpfee on transaction created by bumpfee
285 * "replaced_by_txid" - txid (as HexStr) of transaction created by
286 * bumpfee on transaction replaced by bumpfee
287 * "from", "message" - obsolete fields that could be set in UI prior to
288 * 2011 (removed in commit 4d9b223)
290 * The following keys are serialized in the wallet database, but shouldn't
291 * be read or written through the map (they will be temporarily added and
292 * removed from the map during serialization):
294 * "fromaccount" - serialized strFromAccount value
295 * "n" - serialized nOrderPos value
296 * "timesmart" - serialized nTimeSmart value
297 * "spent" - serialized vfSpent value that existed prior to
298 * 2014 (removed in commit 93a18a3)
301 std::vector
<std::pair
<std::string
, std::string
> > vOrderForm
;
302 unsigned int fTimeReceivedIsTxTime
;
303 unsigned int nTimeReceived
; //!< time received by this node
305 * Stable timestamp that never changes, and reflects the order a transaction
306 * was added to the wallet. Timestamp is based on the block time for a
307 * transaction added as part of a block, or else the time when the
308 * transaction was received if it wasn't part of a block, with the timestamp
309 * adjusted in both cases so timestamp order matches the order transactions
310 * were added to the wallet. More details can be found in
311 * CWallet::ComputeTimeSmart().
313 unsigned int nTimeSmart
;
315 * From me flag is set to 1 for transactions that were created by the wallet
316 * on this bitcoin node, and set to 0 for transactions that were created
317 * externally and came in through the network or sendrawtransaction RPC.
320 std::string strFromAccount
;
321 int64_t nOrderPos
; //!< position in ordered transaction list
324 mutable bool fDebitCached
;
325 mutable bool fCreditCached
;
326 mutable bool fImmatureCreditCached
;
327 mutable bool fAvailableCreditCached
;
328 mutable bool fWatchDebitCached
;
329 mutable bool fWatchCreditCached
;
330 mutable bool fImmatureWatchCreditCached
;
331 mutable bool fAvailableWatchCreditCached
;
332 mutable bool fChangeCached
;
333 mutable CAmount nDebitCached
;
334 mutable CAmount nCreditCached
;
335 mutable CAmount nImmatureCreditCached
;
336 mutable CAmount nAvailableCreditCached
;
337 mutable CAmount nWatchDebitCached
;
338 mutable CAmount nWatchCreditCached
;
339 mutable CAmount nImmatureWatchCreditCached
;
340 mutable CAmount nAvailableWatchCreditCached
;
341 mutable CAmount nChangeCached
;
348 CWalletTx(const CWallet
* pwalletIn
, CTransactionRef arg
) : CMerkleTx(std::move(arg
))
353 void Init(const CWallet
* pwalletIn
)
358 fTimeReceivedIsTxTime
= false;
362 strFromAccount
.clear();
363 fDebitCached
= false;
364 fCreditCached
= false;
365 fImmatureCreditCached
= false;
366 fAvailableCreditCached
= false;
367 fWatchDebitCached
= false;
368 fWatchCreditCached
= false;
369 fImmatureWatchCreditCached
= false;
370 fAvailableWatchCreditCached
= false;
371 fChangeCached
= false;
374 nImmatureCreditCached
= 0;
375 nAvailableCreditCached
= 0;
376 nWatchDebitCached
= 0;
377 nWatchCreditCached
= 0;
378 nAvailableWatchCreditCached
= 0;
379 nImmatureWatchCreditCached
= 0;
384 ADD_SERIALIZE_METHODS
;
386 template <typename Stream
, typename Operation
>
387 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
388 if (ser_action
.ForRead())
392 if (!ser_action
.ForRead())
394 mapValue
["fromaccount"] = strFromAccount
;
396 WriteOrderPos(nOrderPos
, mapValue
);
399 mapValue
["timesmart"] = strprintf("%u", nTimeSmart
);
402 READWRITE(*(CMerkleTx
*)this);
403 std::vector
<CMerkleTx
> vUnused
; //!< Used to be vtxPrev
406 READWRITE(vOrderForm
);
407 READWRITE(fTimeReceivedIsTxTime
);
408 READWRITE(nTimeReceived
);
412 if (ser_action
.ForRead())
414 strFromAccount
= mapValue
["fromaccount"];
416 ReadOrderPos(nOrderPos
, mapValue
);
418 nTimeSmart
= mapValue
.count("timesmart") ? (unsigned int)atoi64(mapValue
["timesmart"]) : 0;
421 mapValue
.erase("fromaccount");
422 mapValue
.erase("spent");
424 mapValue
.erase("timesmart");
427 //! make sure balances are recalculated
430 fCreditCached
= false;
431 fAvailableCreditCached
= false;
432 fImmatureCreditCached
= false;
433 fWatchDebitCached
= false;
434 fWatchCreditCached
= false;
435 fAvailableWatchCreditCached
= false;
436 fImmatureWatchCreditCached
= false;
437 fDebitCached
= false;
438 fChangeCached
= false;
441 void BindWallet(CWallet
*pwalletIn
)
447 //! filter decides which addresses will count towards the debit
448 CAmount
GetDebit(const isminefilter
& filter
) const;
449 CAmount
GetCredit(const isminefilter
& filter
) const;
450 CAmount
GetImmatureCredit(bool fUseCache
=true) const;
451 CAmount
GetAvailableCredit(bool fUseCache
=true) const;
452 CAmount
GetImmatureWatchOnlyCredit(const bool& fUseCache
=true) const;
453 CAmount
GetAvailableWatchOnlyCredit(const bool& fUseCache
=true) const;
454 CAmount
GetChange() const;
456 void GetAmounts(std::list
<COutputEntry
>& listReceived
,
457 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const;
459 bool IsFromMe(const isminefilter
& filter
) const
461 return (GetDebit(filter
) > 0);
464 // True if only scriptSigs are different
465 bool IsEquivalentTo(const CWalletTx
& tx
) const;
467 bool InMempool() const;
468 bool IsTrusted() const;
470 int64_t GetTxTime() const;
471 int GetRequestCount() const;
473 // RelayWalletTransaction may only be called if fBroadcastTransactions!
474 bool RelayWalletTransaction(CConnman
* connman
);
476 std::set
<uint256
> GetConflicts() const;
482 CInputCoin(const CWalletTx
* walletTx
, unsigned int i
)
485 throw std::invalid_argument("walletTx should not be null");
486 if (i
>= walletTx
->tx
->vout
.size())
487 throw std::out_of_range("The output index is out of range");
489 outpoint
= COutPoint(walletTx
->GetHash(), i
);
490 txout
= walletTx
->tx
->vout
[i
];
496 bool operator<(const CInputCoin
& rhs
) const {
497 return outpoint
< rhs
.outpoint
;
500 bool operator!=(const CInputCoin
& rhs
) const {
501 return outpoint
!= rhs
.outpoint
;
504 bool operator==(const CInputCoin
& rhs
) const {
505 return outpoint
== rhs
.outpoint
;
516 /** Whether we have the private keys to spend this output */
519 /** Whether we know how to spend this output, ignoring the lack of keys */
523 * Whether this output is considered safe to spend. Unconfirmed transactions
524 * from outside keys and unconfirmed replacement transactions are considered
525 * unsafe and will not be used to fund new spending transactions.
529 COutput(const CWalletTx
*txIn
, int iIn
, int nDepthIn
, bool fSpendableIn
, bool fSolvableIn
, bool fSafeIn
)
531 tx
= txIn
; i
= iIn
; nDepth
= nDepthIn
; fSpendable
= fSpendableIn
; fSolvable
= fSolvableIn
; fSafe
= fSafeIn
;
534 std::string
ToString() const;
540 /** Private key that includes an expiration date in case it never gets used. */
545 int64_t nTimeCreated
;
546 int64_t nTimeExpires
;
547 std::string strComment
;
548 //! todo: add something to note what created it (user, getnewaddress, change)
549 //! maybe should have a map<string, string> property map
551 explicit CWalletKey(int64_t nExpires
=0);
553 ADD_SERIALIZE_METHODS
;
555 template <typename Stream
, typename Operation
>
556 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
557 int nVersion
= s
.GetVersion();
558 if (!(s
.GetType() & SER_GETHASH
))
560 READWRITE(vchPrivKey
);
561 READWRITE(nTimeCreated
);
562 READWRITE(nTimeExpires
);
563 READWRITE(LIMITED_STRING(strComment
, 65536));
568 * Internal transfers.
569 * Database key is acentry<account><counter>.
571 class CAccountingEntry
574 std::string strAccount
;
575 CAmount nCreditDebit
;
577 std::string strOtherAccount
;
578 std::string strComment
;
580 int64_t nOrderPos
; //!< position in ordered transaction list
593 strOtherAccount
.clear();
599 ADD_SERIALIZE_METHODS
;
601 template <typename Stream
, typename Operation
>
602 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
603 int nVersion
= s
.GetVersion();
604 if (!(s
.GetType() & SER_GETHASH
))
606 //! Note: strAccount is serialized as part of the key, not here.
607 READWRITE(nCreditDebit
);
609 READWRITE(LIMITED_STRING(strOtherAccount
, 65536));
611 if (!ser_action
.ForRead())
613 WriteOrderPos(nOrderPos
, mapValue
);
615 if (!(mapValue
.empty() && _ssExtra
.empty()))
617 CDataStream
ss(s
.GetType(), s
.GetVersion());
618 ss
.insert(ss
.begin(), '\0');
620 ss
.insert(ss
.end(), _ssExtra
.begin(), _ssExtra
.end());
621 strComment
.append(ss
.str());
625 READWRITE(LIMITED_STRING(strComment
, 65536));
627 size_t nSepPos
= strComment
.find("\0", 0, 1);
628 if (ser_action
.ForRead())
631 if (std::string::npos
!= nSepPos
)
633 CDataStream
ss(std::vector
<char>(strComment
.begin() + nSepPos
+ 1, strComment
.end()), s
.GetType(), s
.GetVersion());
635 _ssExtra
= std::vector
<char>(ss
.begin(), ss
.end());
637 ReadOrderPos(nOrderPos
, mapValue
);
639 if (std::string::npos
!= nSepPos
)
640 strComment
.erase(nSepPos
);
646 std::vector
<char> _ssExtra
;
651 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
652 * and provides the ability to create new transactions.
654 class CWallet
: public CCryptoKeyStore
, public CValidationInterface
657 static std::atomic
<bool> fFlushScheduled
;
658 std::atomic
<bool> fAbortRescan
;
659 std::atomic
<bool> fScanningWallet
;
662 * Select a set of coins such that nValueRet >= nTargetValue and at least
663 * all coins from coinControl are selected; Never select unconfirmed coins
664 * if they are not ours
666 bool SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
*coinControl
= nullptr) const;
668 CWalletDB
*pwalletdbEncryption
;
670 //! the current wallet version: clients below this version are not able to load the wallet
673 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
674 int nWalletMaxVersion
;
678 bool fBroadcastTransactions
;
681 * Used to keep track of spent outpoints, and
682 * detect and report conflicts (double-spends or
683 * mutated transactions where the mutant gets mined).
685 typedef std::multimap
<COutPoint
, uint256
> TxSpends
;
686 TxSpends mapTxSpends
;
687 void AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
);
688 void AddToSpends(const uint256
& wtxid
);
690 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
691 void MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
);
693 void SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
>);
695 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
696 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
697 void SyncTransaction(const CTransactionRef
& tx
, const CBlockIndex
*pindex
= nullptr, int posInBlock
= 0);
699 /* the HD chain data model (external chain counters) */
702 /* HD derive new child key (on internal or external chain) */
703 void DeriveNewChildKey(CWalletDB
&walletdb
, CKeyMetadata
& metadata
, CKey
& secret
, bool internal
= false);
705 std::set
<int64_t> setInternalKeyPool
;
706 std::set
<int64_t> setExternalKeyPool
;
707 int64_t m_max_keypool_index
;
708 std::map
<CKeyID
, int64_t> m_pool_key_to_index
;
710 int64_t nTimeFirstKey
;
713 * Private version of AddWatchOnly method which does not accept a
714 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
715 * the watch key did not previously have a timestamp associated with it.
716 * Because this is an inherited virtual method, it is accessible despite
717 * being marked private, but it is marked private anyway to encourage use
718 * of the other AddWatchOnly which accepts a timestamp and sets
719 * nTimeFirstKey more intelligently for more efficient rescans.
721 bool AddWatchOnly(const CScript
& dest
) override
;
723 std::unique_ptr
<CWalletDBWrapper
> dbw
;
728 * This lock protects all the fields added by CWallet.
730 mutable CCriticalSection cs_wallet
;
732 /** Get database handle used by this wallet. Ideally this function would
735 CWalletDBWrapper
& GetDBHandle()
740 /** Get a name for this wallet for logging/debugging purposes.
742 std::string
GetName() const
745 return dbw
->GetName();
751 void LoadKeyPool(int64_t nIndex
, const CKeyPool
&keypool
);
753 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
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())
767 // Create wallet with passed-in database handle
768 explicit CWallet(std::unique_ptr
<CWalletDBWrapper
> dbw_in
) : dbw(std::move(dbw_in
))
775 delete pwalletdbEncryption
;
776 pwalletdbEncryption
= nullptr;
781 nWalletVersion
= FEATURE_BASE
;
782 nWalletMaxVersion
= FEATURE_BASE
;
784 pwalletdbEncryption
= nullptr;
786 nAccountingEntryNumber
= 0;
789 m_max_keypool_index
= 0;
791 fBroadcastTransactions
= false;
793 fAbortRescan
= false;
794 fScanningWallet
= false;
797 std::map
<uint256
, CWalletTx
> mapWallet
;
798 std::list
<CAccountingEntry
> laccentries
;
800 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
801 typedef std::multimap
<int64_t, TxPair
> TxItems
;
804 int64_t nOrderPosNext
;
805 uint64_t nAccountingEntryNumber
;
806 std::map
<uint256
, int> mapRequestCount
;
808 std::map
<CTxDestination
, CAddressBookData
> mapAddressBook
;
810 CPubKey vchDefaultKey
;
812 std::set
<COutPoint
> setLockedCoins
;
814 const CWalletTx
* GetWalletTx(const uint256
& hash
) const;
816 //! check whether we are allowed to upgrade (or already support) to the named feature
817 bool CanSupportFeature(enum WalletFeature wf
) const { AssertLockHeld(cs_wallet
); return nWalletMaxVersion
>= wf
; }
820 * populate vCoins with vector of available COutputs.
822 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;
825 * Return list of available coins and locked coins grouped by non-change output address.
827 std::map
<CTxDestination
, std::vector
<COutput
>> ListCoins() const;
830 * Find non-change parent output.
832 const CTxOut
& FindNonChangeParentOutput(const CTransaction
& tx
, int output
) const;
835 * Shuffle and select coins until nTargetValue is reached while avoiding
836 * small change; This method is stochastic for some inputs and upon
837 * completion the coin set and corresponding actual target value is
840 bool SelectCoinsMinConf(const CAmount
& nTargetValue
, int nConfMine
, int nConfTheirs
, uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
) const;
842 bool IsSpent(const uint256
& hash
, unsigned int n
) const;
844 bool IsLockedCoin(uint256 hash
, unsigned int n
) const;
845 void LockCoin(const COutPoint
& output
);
846 void UnlockCoin(const COutPoint
& output
);
847 void UnlockAllCoins();
848 void ListLockedCoins(std::vector
<COutPoint
>& vOutpts
) const;
851 * Rescan abort properties
853 void AbortRescan() { fAbortRescan
= true; }
854 bool IsAbortingRescan() { return fAbortRescan
; }
855 bool IsScanning() { return fScanningWallet
; }
858 * keystore implementation
861 CPubKey
GenerateNewKey(CWalletDB
& walletdb
, bool internal
= false);
862 //! Adds a key to the store, and saves it to disk.
863 bool AddKeyPubKey(const CKey
& key
, const CPubKey
&pubkey
) override
;
864 bool AddKeyPubKeyWithDB(CWalletDB
&walletdb
,const CKey
& key
, const CPubKey
&pubkey
);
865 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
866 bool LoadKey(const CKey
& key
, const CPubKey
&pubkey
) { return CCryptoKeyStore::AddKeyPubKey(key
, pubkey
); }
867 //! Load metadata (used by LoadWallet)
868 bool LoadKeyMetadata(const CTxDestination
& pubKey
, const CKeyMetadata
&metadata
);
870 bool LoadMinVersion(int nVersion
) { AssertLockHeld(cs_wallet
); nWalletVersion
= nVersion
; nWalletMaxVersion
= std::max(nWalletMaxVersion
, nVersion
); return true; }
871 void UpdateTimeFirstKey(int64_t nCreateTime
);
873 //! Adds an encrypted key to the store, and saves it to disk.
874 bool AddCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
) override
;
875 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
876 bool LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
);
877 bool AddCScript(const CScript
& redeemScript
) override
;
878 bool LoadCScript(const CScript
& redeemScript
);
880 //! Adds a destination data tuple to the store, and saves it to disk
881 bool AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
882 //! Erases a destination data tuple in the store and on disk
883 bool EraseDestData(const CTxDestination
&dest
, const std::string
&key
);
884 //! Adds a destination data tuple to the store, without saving it to disk
885 bool LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
886 //! Look up a destination data tuple in the store, return true if found false otherwise
887 bool GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const;
888 //! Get all destination values matching a prefix.
889 std::vector
<std::string
> GetDestValues(const std::string
& prefix
) const;
891 //! Adds a watch-only address to the store, and saves it to disk.
892 bool AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
);
893 bool RemoveWatchOnly(const CScript
&dest
) override
;
894 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
895 bool LoadWatchOnly(const CScript
&dest
);
897 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
900 bool Unlock(const SecureString
& strWalletPassphrase
);
901 bool ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
);
902 bool EncryptWallet(const SecureString
& strWalletPassphrase
);
904 void GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const;
905 unsigned int ComputeTimeSmart(const CWalletTx
& wtx
) const;
908 * Increment the next transaction order id
909 * @return next transaction order id
911 int64_t IncOrderPosNext(CWalletDB
*pwalletdb
= nullptr);
912 DBErrors
ReorderTransactions();
913 bool AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
= "");
914 bool GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
= false);
917 bool AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
=true);
918 bool LoadToWallet(const CWalletTx
& wtxIn
);
919 void TransactionAddedToMempool(const CTransactionRef
& tx
) override
;
920 void BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
*pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) override
;
921 void BlockDisconnected(const std::shared_ptr
<const CBlock
>& pblock
) override
;
922 bool AddToWalletIfInvolvingMe(const CTransactionRef
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
);
923 int64_t RescanFromTime(int64_t startTime
, bool update
);
924 CBlockIndex
* ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
= false);
925 void ReacceptWalletTransactions();
926 void ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
) override
;
927 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
928 std::vector
<uint256
> ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
);
929 CAmount
GetBalance() const;
930 CAmount
GetUnconfirmedBalance() const;
931 CAmount
GetImmatureBalance() const;
932 CAmount
GetWatchOnlyBalance() const;
933 CAmount
GetUnconfirmedWatchOnlyBalance() const;
934 CAmount
GetImmatureWatchOnlyBalance() const;
935 CAmount
GetLegacyBalance(const isminefilter
& filter
, int minDepth
, const std::string
* account
) const;
936 CAmount
GetAvailableBalance(const CCoinControl
* coinControl
= nullptr) const;
939 * Insert additional inputs into the transaction by
940 * calling CreateTransaction();
942 bool FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, int& nChangePosInOut
, std::string
& strFailReason
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, CCoinControl
);
943 bool SignTransaction(CMutableTransaction
& tx
);
946 * Create a new transaction paying the recipients with a set of coins
947 * selected by SelectCoins(); Also create the change output, when needed
948 * @note passing nChangePosInOut as -1 will result in setting a random position
950 bool CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
, int& nChangePosInOut
,
951 std::string
& strFailReason
, const CCoinControl
& coin_control
, bool sign
= true);
952 bool CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
);
954 void ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
);
955 bool AddAccountingEntry(const CAccountingEntry
&);
956 bool AddAccountingEntry(const CAccountingEntry
&, CWalletDB
*pwalletdb
);
957 template <typename ContainerType
>
958 bool DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
) const;
960 static CFeeRate minTxFee
;
961 static CFeeRate fallbackFee
;
962 static CFeeRate m_discard_rate
;
964 * Estimate the minimum fee considering user set parameters
965 * and the required fee
967 static CAmount
GetMinimumFee(unsigned int nTxBytes
, const CCoinControl
& coin_control
, const CTxMemPool
& pool
, const CBlockPolicyEstimator
& estimator
, FeeCalculation
*feeCalc
);
969 * Return the minimum required fee taking into account the
970 * floating relay fee and user set minimum transaction fee
972 static CAmount
GetRequiredFee(unsigned int nTxBytes
);
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
; }
987 /** Does the wallet have at least min_keys in the keypool? */
988 bool HasUnusedKeys(int min_keys
) 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
1029 std::map
<uint256
, int>::iterator mi
= mapRequestCount
.find(hash
);
1030 if (mi
!= mapRequestCount
.end())
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
= nullptr, 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 //! Responsible for reading and validating the -wallet arguments and verifying the wallet database.
1064 // This function will perform salvage on the wallet if requested, as long as only one wallet is
1065 // being loaded (CWallet::ParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet).
1066 static bool Verify();
1069 * Address book entry changed.
1070 * @note called with lock cs_wallet held.
1072 boost::signals2::signal
<void (CWallet
*wallet
, const CTxDestination
1073 &address
, const std::string
&label
, bool isMine
,
1074 const std::string
&purpose
,
1075 ChangeType status
)> NotifyAddressBookChanged
;
1078 * Wallet transaction added, removed or updated.
1079 * @note called with lock cs_wallet held.
1081 boost::signals2::signal
<void (CWallet
*wallet
, const uint256
&hashTx
,
1082 ChangeType status
)> NotifyTransactionChanged
;
1084 /** Show progress e.g. for rescan */
1085 boost::signals2::signal
<void (const std::string
&title
, int nProgress
)> ShowProgress
;
1087 /** Watch-only address added */
1088 boost::signals2::signal
<void (bool fHaveWatchOnly
)> NotifyWatchonlyChanged
;
1090 /** Inquire whether this wallet broadcasts transactions. */
1091 bool GetBroadcastTransactions() const { return fBroadcastTransactions
; }
1092 /** Set whether this wallet broadcasts transactions. */
1093 void SetBroadcastTransactions(bool broadcast
) { fBroadcastTransactions
= broadcast
; }
1095 /** Return whether transaction can be abandoned */
1096 bool TransactionCanBeAbandoned(const uint256
& hashTx
) const;
1098 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1099 bool AbandonTransaction(const uint256
& hashTx
);
1101 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1102 bool MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
);
1104 /* Returns the wallets help message */
1105 static std::string
GetWalletHelpString(bool showDebug
);
1107 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1108 static CWallet
* CreateWalletFromFile(const std::string walletFile
);
1109 static bool InitLoadWallet();
1112 * Wallet post-init setup
1113 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1115 void postInitProcess(CScheduler
& scheduler
);
1117 /* Wallets parameter interaction */
1118 static bool ParameterInteraction();
1120 bool BackupWallet(const std::string
& strDest
);
1122 /* Set the HD chain model (chain child index counters) */
1123 bool SetHDChain(const CHDChain
& chain
, bool memonly
);
1124 const CHDChain
& GetHDChain() const { return hdChain
; }
1126 /* Returns true if HD is enabled */
1127 bool IsHDEnabled() const;
1129 /* Generates a new HD master key (will not be activated) */
1130 CPubKey
GenerateNewHDMasterKey();
1132 /* Set the current HD master key (will reset the chain child index counters)
1133 Sets the master key's version based on the current wallet version (so the
1134 caller must ensure the current wallet version is correct before calling
1136 bool SetHDMasterKey(const CPubKey
& key
);
1139 /** A key allocated from the key pool. */
1140 class CReserveKey
: public CReserveScript
1148 explicit CReserveKey(CWallet
* pwalletIn
)
1151 pwallet
= pwalletIn
;
1155 CReserveKey() = default;
1156 CReserveKey(const CReserveKey
&) = delete;
1157 CReserveKey
& operator=(const CReserveKey
&) = delete;
1165 bool GetReservedKey(CPubKey
&pubkey
, bool internal
= false);
1167 void KeepScript() override
{ KeepKey(); }
1172 * Account information.
1173 * Stored in wallet with key "acc"+string account name.
1187 vchPubKey
= CPubKey();
1190 ADD_SERIALIZE_METHODS
;
1192 template <typename Stream
, typename Operation
>
1193 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
1194 int nVersion
= s
.GetVersion();
1195 if (!(s
.GetType() & SER_GETHASH
))
1196 READWRITE(nVersion
);
1197 READWRITE(vchPubKey
);
1201 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1202 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1203 // so that each entry corresponds to each vIn, in order.
1204 template <typename ContainerType
>
1205 bool CWallet::DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
) const
1207 // Fill in dummy signatures for fee calculation.
1209 for (const auto& coin
: coins
)
1211 const CScript
& scriptPubKey
= coin
.txout
.scriptPubKey
;
1212 SignatureData sigdata
;
1214 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey
, sigdata
))
1218 UpdateTransaction(txNew
, nIn
, sigdata
);
1226 #endif // BITCOIN_WALLET_WALLET_H